예제 #1
0
파일: client.py 프로젝트: bookug/SiGuo
class Client(NetStream, GObject):
    def __init__(self, headMode=8, serverIP="127.0.0.1", serverPort=4829, sleepInterval=0.1, parent=None):
        NetStream.__init__(self, headMode)
        GObject.__init__(self)
        print("client init: %s %s" % (serverIP, serverPort))
        self.InitData(serverIP, serverPort, sleepInterval, parent)
        self.setup()

        # define a signal and its handler, then each time this
        # siganl isa emitted, handler function will be called
        # self.parent.parent.connect(self, QtCore.SIGNAL('serverCrashedAlert()', self.parent.parent.serverCrashedAlert))
        __gsignals__ = {"serverCrashedAlert": (GObject.SIGNAL_RUN_FIRST, None, (int,))}

        def do_serverCrashedAlert(self, arg):
            print("class method for `serverCrashedAlert` called with argument", arg)
            print("server is crashed")

    def InitData(self, serverIP, serverPort, sleepInterval, parent):
        self.serverIP = serverIP
        self.serverPort = serverPort
        self.sleepInterval = sleepInterval
        self.dispatcher = Dispatcher()
        self.parent = parent
        self.isAlive = True
        self.hasBegun = False

    def killClient(self):
        self.isAlive = False

    def setup(self):
        self.setupDispatcher()
        self.setupClient()

    def setupDispatcher(self):
        self.dispatcher.setParent(self)
        services = {
            1001: LoginService(self.dispatcher),
            # 1002 : HallService(self.dispatcher),
            # 1003 : RoomService(self.dispatcher)
        }
        self.dispatcher.registers(services)

    def setupClient(self):
        print(self.serverPort + "\n" + self.serverIP)
        self.connect(self.serverIP, self.serverPort)
        self.nodelay(0)
        self.nodelay(1)

    def sendToServer(self, serviceID, commandID, data):
        message = {}
        message["create_time"] = time.time()
        message["service_id"] = serviceID
        message["command_id"] = commandID
        message["data"] = data
        try:
            messageString = json.dumps(message)
        except (TypeError, e):
            print("error while dumping json")
            print(e)
            print(message)
        print("sending message: %s" % (message))
        self.send(messageString)

    def run(self, lock):  # WARN:lock is not used
        try:
            while self.isAlive:
                time.sleep(self.sleepInterval)
                self.process()
                if self.state == net.NET_STATE_ESTABLISHED:
                    self.hasBegun = True
                if sel.hasBegun == True:
                    print("current state: ", self.state)
                    if self.state == NET_STATE_STOP:
                        # emit the signal, only to self in GTK+
                        # self.emit(QtCore.SIGNAL('serverCrashedAlert()'))
                        self.emit("serverCrashedAlert", 100000000)
                        self.isAlive = False
                    messageString = self.recv()
                    if messageString == "":
                        continue
                    else:
                        print("message: ", messageString)
                    try:
                        message = json.loads(messageString)
                    except (ValueError, e):
                        message = messageString
                    self.dispatcher.dispatch(message, self)
        except (BaseException, e):
            print(time.ctime(), ": error in running client")
            print(e)
예제 #2
0
파일: main.py 프로젝트: bookug/SiGuo
class Main(NetHost):    #GObject?

    def __init__(self, headMode = 8, port = 4829, timeInterval = 10000, sleepInterval = 0.5):
        NetHost.__init__(self, headMode)
        self.InitData(headMode,port,timeInterval,sleepInterval)
        self.setup()

    def InitData(self,headMode,port,timeInterval,sleepInterval):
        self.database = Database()
        try:
            self.headMode = headMode
            self.port = port
            self.timerInterval = timeInterval
            self.sleepInterval = sleepInterval
            self.dispatcher = Dispatcher()
            self.connectedClients = {}
            print ("Type of clients = ",type(self.connectedClients))
        except BaseException as e:
            print ("Error while server init data")
            print (e)

    def __del__(self):
        print ("Server Lost!")

    def setup(self):
        self.setupDatabase()
        self.setupDispatcher()
        self.setupServer()
        print (self.connectedClients)

    def setupServer(self):
        try:
            self.startup(self.port)
            print ('[',time.ctime(),']','Server startup at port:',self.port)
            self.settimer(self.timerInterval)
        except BaseException as e:
            print ("Error while setup server")
            print (e)

    def setupDispatcher(self):
        self.dispatcher.setParent(self)
        services = {}
        #services[LoginService.serviceID] = LoginService(self.dispatcher)
        #services[HallService.serviceID]  = HallService(self.dispatcher)
        #services[RoomService.serviceID] = RoomService(self.dispatcher)
        self.dispatcher.registers(services)
        print ("Setup Dispatcher")
        print (services)

    def setupDatabase(self):
        self.database.connect()
        try:
            self.database.setup()
        except BaseException as e:
            print ("Error while setup db")
            print (e)

    def hasNicknameInConnectedClients(self,nickname):
        for connectID in self.connectedClients:
            if self.connectedClients[connectID].nickname == nickname:
                print ("Has Nickname connected!!")
                print (connectID," ",nickname)
                return True
        return False

    @staticmethod
    def logTime():
        print ("[",time.ctime(),"]")

    @staticmethod
    def log(string):
        try:
            Main.logTime()
            print (string)
        except BaseException as e:
            print ("Error while finding log",e)

    def connectionEventHandler(self,connectID,messageString = ''):
        print ("clientsType is ",type(self.connectedClients))
        try:
            self.log(str(connectID) + " comes")
            self.connectedClients[connectID] = Player.Player(connectID,self)
            #self.sendToClient(connectID,1001,1001,"F**k you in connection handler")
        except BaseException as e:
            self.log("Error in Connection Event")
            print (type(self.connectedClients))
            print (e)

    def disconnectionEventHandler(self,connectID,messageString = ''):
        try:
            self.log(str(connectID) + ' leaves')
            del self.connectedClients[connectID]
            self.dispatcher.services[1002].leaveHall(connectID)
            self.dispatcher.services[1003].removePlayerFromAllRooms(connectID)
        except BaseException as e:
            self.log("Error in disconnect")
            print (e)

    def timerEventHandler(self,connectID,messageString = ''):
        #self.log(str(connectID) + ":timer triggered!")
        #print "Clients type = " ,type(self.connectedClients)
        pass

    def messageEventHandler(self,connectID,message = ''):
        try:
            self.log(str(connectID) + " sends a message!")
            self.dispatcher.dispatch(message,self.connectedClients[connectID])
            #self.sendToClient(connectID,1001,1001,"F**k you in messageEventHandler")
        except BaseException as e:
            self.log("Error in message Event Handler")
            print (message)
            print (e)

    def sendToClient(self,connectID,serviceID,commandID,data):
        message = {}
        message['create_time'] = time.time()
        message['service_id'] = serviceID
        message['command_id'] = commandID
        message['data'] = data

        messageString = json.dumps(message)
        self.send(connectID,messageString)
        print ("Send message To ",connectID,":",messageString)

    def run(self):
    #try:
        while True:
            try:
                try:
                    time.sleep(self.sleepInterval)
                except BaseException as e:
                    print ("Error while Server Sleep")
                    print (e)
                try:
                    try:
                        self.process()
                    except BaseException as e:
                        print ("Error while Server Processing!")
                        print (e)
                    try:
                        eventType , connectID , lparam ,messageString = self.read()
                    except BaseException as e:
                        print ("Error while Server Reading()")
                    try:
                        if eventType < 0:
                            #print "Wrong Event:",eventType
                            continue
                    except BaseException as e:
                        print ("Errow while Finding Wrong Event")
                    try:
                        if eventType == net.NET_NEW:
                            self.connectionEventHandler(connectID,messageString)
                        if eventType == net.NET_LEAVE:
                            self.disconnectionEventHandler(connectID,messageString)
                        if eventType == net.NET_TIMER:
                            self.timerEventHandler(connectID,messageString)
                        if eventType == net.NET_DATA:
                            #self.sendToClient(connectID,1001,1001,"F**k you in NETDATA")
                            message = None
                            try:
                                message = json.loads(messageString)
                                self.messageEventHandler(connectID,message)
                            except BaseException as e:
                                self.logTime()
                                print (e)
                    except BaseException as e:
                        self.log("Error while handling Event")
                        print (e)
                except BaseException as e:
                    print ("Error while server working in loop")
                    print (e)
            except KeyboardInterrupt:
                print ("to quit the server")
                break
            except BaseException as e:
                print ("Error while server loop")
                print (e)