Exemplo n.º 1
0
class LoginServer:
    def __init__(self, port, backlog=1000, compress=False):
        self.port = port
        self.backlog = backlog
        self.compress = compress

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.db = DataBase()
        # This is for pre-login
        self.tempConnections = []
        # This is for authed clients
        self.activeConnections = []

        # Temp user dict
        self.clients = {}

        self.connect(self.port, self.backlog)
        self.startPolling()

    def connect(self, port, backlog=1000):
        # Bind to our socket
        tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener.addConnection(tcpSocket)

    def startPolling(self):
        taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
        taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask", -39)

    def tskListenerPolling(self, task):
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConnection = PointerToConnection()

            if self.cListener.getNewConnection(rendezvous, netAddress, newConnection):
                newConnection = newConnection.p()
                self.tempConnections.append(newConnection)  # Lets add it to a temp list first.
                self.cReader.addConnection(newConnection)  # Begin reading connection

                # Make the temp place holder then add to temp, under dataget check the temp list, if something ther do
                # auth and then add to the active
        return Task.cont

    def tskDisconnectPolling(self, task):
        while self.cManager.resetConnectionAvailable() == True:
            print "disconnect"
            connPointer = PointerToConnection()
            self.cManager.getResetConnection(connPointer)
            connection = connPointer.p()

            # Remove the connection we just found to be "reset" or "disconnected"
            self.cReader.removeConnection(connection)
            # Remove the connection we just found to be "reset" or "disconnected"
            self.cReader.removeConnection(connection)
            for u in range(len(self.clients)):
                if self.clients[u]["connection"] == connection:
                    del self.clients[u]
                    break

                    # Loop through the activeConnections till we find the connection we just deleted
                    # and remove it from our activeConnections list
            for c in range(0, len(self.activeConnections)):
                if self.activeConnections[c] == connection:
                    del self.activeConnections[c]
                    break

        return Task.cont

    def broadcastData(self, data):
        # Broadcast data out to all activeConnections
        for con in self.activeConnections:
            self.sendData(data, con)

    def processData(self, netDatagram):
        myIterator = PyDatagramIterator(netDatagram)
        return self.decode(myIterator.getString())

    def getClients(self):
        # return a list of all activeConnections
        return self.activeConnections

    def encode(self, data, compress=False):
        # encode(and possibly compress) the data with rencode
        return rencode.dumps(data, compress)

    def decode(self, data):
        # decode(and possibly decompress) the data with rencode
        return rencode.loads(data)

    def sendData(self, data, con):
        myPyDatagram = PyDatagram()
        myPyDatagram.addString(self.encode(data, self.compress))
        self.cWriter.send(myPyDatagram, con)

        # This will check and do the logins.

    def auth(self, datagram):
        # If in login state.
        clientIp = datagram.getAddress()  # This is the ip :P
        clientCon = datagram.getConnection()  # This is the connection data. used to send the shit.
        package = self.processData(datagram)
        print "SERVER: ", package
        valid_packet = False
        if len(package) == 2:
            # if login request is send reply
            # Should add a checker like in the db something like isLogged(0 or 1)
            # If found then say no for client
            user_found = False
            if package[0] == "login_request":
                valid_packet = True
                print "Try login"
                for u in range(len(self.clients)):
                    if self.clients[u]["name"] == package[1][0]:
                        print "User already exists"
                        user_found = True
                        data = {}
                        data[0] = "error"
                        data[1] = "User already logged in"
                        self.sendData(data, clientCon)
                        break
                        # send something back to the client saying to change username
                if not user_found:
                    username = package[1][0]
                    password = package[1][1]
                    self.db.Client_getLogin(username, password)
                    if self.db.login_valid:
                        # Add the user
                        new_user = {}
                        new_user["name"] = package[1][0]
                        new_user["connection"] = clientCon
                        new_user["ready"] = False
                        new_user["new_dest"] = False
                        new_user["new_spell"] = False
                        self.clients[len(self.clients)] = new_user
                        # Send back the valid check.
                        data = {}
                        data[0] = "login_valid"  # If client gets this the client should switch to main_menu.
                        data[1] = {}
                        data[1][0] = self.db.status
                        data[1][1] = len(self.clients) - 1  # This is part of the old 'which' packet
                        self.sendData(data, clientCon)

                        # Move client to the self.activeConnections list.
                        self.activeConnections.append(clientCon)
                        print "HERE IS ACTIVE: ", self.activeConnections
                        self.tempConnections.remove(clientCon)
                        print "HERE IS TEMP", self.tempConnections

                else:
                    status = self.db.status
                    data = {}
                    data[0] = "db_reply"
                    data[1] = status
                    self.sendData(data, clientCon)
            if not valid_packet:
                data = {}
                data[0] = "error"
                data[1] = "Wrong Packet"
                self.sendData(data, clientCon)
                print "Login Packet not correct"

        else:
            print "Data in packet wrong size"

    def getData(self):
        data = []
        while self.cReader.dataAvailable():
            datagram = NetDatagram()  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):

                if datagram.getConnection() in self.tempConnections:
                    print "Check Auth!"
                    self.auth(datagram)
                    print "Auth Done!"
                    # in auth def or after the connection will be moved to self.activeConnections
                    # and then removed from the temp list
                    break
                    # Check if the data rechieved is from a valid client.
                elif datagram.getConnection() in self.activeConnections:
                    appendage = {}
                    appendage[0] = self.processData(datagram)
                    appendage[1] = datagram.getConnection()
                    data.append(appendage)

        return data
class SocketServer():
    def __init__(self, port, virtual_world, camera_mgr, sync_session):
        self.port = port
        self.virtual_world = virtual_world
        self.cam_mgr = camera_mgr

        self.task_mgr = virtual_world.taskMgr
        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cReader.setRawMode(True)
        self.cWriter = ConnectionWriter(self.cManager, 1)
        self.cWriter.setRawMode(True)
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, BACKLOG)
        self.cListener.addConnection(self.tcpSocket)

        self.activeSessions = {}
        self.connection_map = {}
        self.set_handlers()

        hostname = socket.gethostname()
        a, b, address_list = socket.gethostbyname_ex(hostname)
        self.ip = address_list[0]
        logging.info("Addresses %s" % address_list)
        logging.info("Server is running on ip: %s, port: %s" %
                     (self.ip, self.port))

        self.client_counter = 0
        self.read_buffer = ''
        self.read_state = 0
        self.read_body_length = 0
        self.packet = SocketPacket()

        controller = virtual_world.getController()
        self.sync = Sync(self.task_mgr, controller, camera_mgr, sync_session)
        self.vv_id = None
        if sync_session:
            logging.info("Waiting for Sync Client!")

        self.showing_info = False
        virtual_world.accept("i", self.toggleInfo)
        self.sync_session = sync_session
        self.createInfoLabel()

        atexit.register(self.exit)

    def createInfoLabel(self):

        string = self.generateInfoString()
        self.info_label = OST(string,
                              pos=(-1.3, -0.5),
                              fg=(1, 1, 1, 1),
                              bg=(0, 0, 0, 0.7),
                              scale=0.05,
                              align=TextNode.ALeft)
        self.info_label.hide()

    def generateInfoString(self, ):
        string = " IP:\t%s  \n" % self.ip
        string += " PORT:\t%s \n" % self.port
        if self.sync_session:
            string += " MODE:\tSync Client\n"
            string += " VV ID:\t%s\n" % self.vv_id
        else:
            string += " MODE:\tAutomatic\n"

        cameras = self.cam_mgr.getCameras()
        num_cameras = len(cameras)

        for camera in cameras:
            id = camera.getId()
            type = camera.getTypeString()
            string += " Cam%s:\t%s\n" % (id, type)
        string += "\n"
        return string

    def set_handlers(self):
        self.task_mgr.add(self.connection_polling, "Poll new connections", -39)
        self.task_mgr.add(self.reader_polling, "Poll reader", -40)
        self.task_mgr.add(self.disconnection_polling, "PollDisconnections",
                          -41)

    def connection_polling(self, taskdata):
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConn = PointerToConnection()
            if self.cListener.getNewConnection(rendezvous, netAddress,
                                               newConn):
                conn = newConn.p()
                self.cReader.addConnection(conn)  # Begin reading connection
                conn_id = self.client_counter
                logging.info("New Connection from ip:%s, conn:%s" %
                             (conn.getAddress(), conn_id))
                self.connection_map[conn_id] = conn
                self.client_counter += 1
                message = eVV_ACK_OK(self.ip, self.port, conn_id)
                self.sendMessage(message, conn)

        return Task.cont

    def reader_polling(self, taskdata):

        if self.cReader.dataAvailable():
            datagram = NetDatagram(
            )  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                self.read_buffer = self.read_buffer + datagram.getMessage()
        while (True):
            if self.read_state == 0:
                if len(self.read_buffer) >= self.packet.header_length:
                    bytes_consumed = self.packet.header_length
                    self.packet.header = self.read_buffer[:bytes_consumed]
                    self.read_body_length = self.packet.decode_header()
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 1
                else:
                    break
            if self.read_state == 1:
                if len(self.read_buffer) >= self.read_body_length:
                    bytes_consumed = self.read_body_length
                    self.packet.data = self.read_buffer[:bytes_consumed]
                    self.packet.offset = 0
                    self.read_body_length = 0
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 0
                    self.new_data_callback(self.packet)

                else:
                    break
        return Task.cont

    def new_data_callback(self, packet):
        packet = copy.deepcopy(packet)
        message_type = packet.get_int()
        conn_id = packet.get_int()
        if message_type == VP_SESSION:
            conn = self.connection_map[conn_id]
            type = packet.get_char()
            pipeline = packet.get_char()
            logging.debug("Received VP_SESSION message from conn:%s, " \
                          "type=%s, pipeline=%s"
                          %(conn_id, VP_TYPE[type], PIPELINE[pipeline]))
            self.newVPSession(conn, type, pipeline, conn_id)

        elif message_type == SYNC_SESSION:
            vv_id = packet.get_int()
            self.vv_id = vv_id
            string = self.generateInfoString()
            self.info_label.setText(string)
            conn = self.connection_map[conn_id]
            logging.debug("Received SYNC_SESSION message from conn:%s" %
                          conn_id)
            self.newSyncSession(conn, conn_id, vv_id)
            logging.info("Sync client connected")

        elif message_type == VP_REQ_CAM_LIST:
            logging.debug("Received VP_REQ_CAM_LIST message from conn:%s" %
                          conn_id)
            cameras = self.cam_mgr.getCameras()
            pipeline = self.activeSessions[conn_id].getPipeline()
            camera_type = None
            if pipeline == STATIC_PIPELINE:
                camera_type = VP_STATIC_CAMERA
            elif pipeline == PTZ_PIPELINE:
                camera_type = VP_ACTIVE_CAMERA
            cam_list = []
            for camera in cameras:
                if camera_type == camera.getType() and not camera.hasSession():
                    cam_list.append(camera.getId())
            message = eVV_CAM_LIST(self.ip, self.port, cam_list)
            conn = self.connection_map[conn_id]
            logging.debug("Sent VV_CAM_LIST message to conn:%s" % conn_id)
            self.sendMessage(message, conn)

        elif message_type == VP_REQ_IMG:
            cam_id = packet.get_int()
            frequency = packet.get_char()
            width = packet.get_int()
            height = packet.get_int()
            jpeg = packet.get_bool()
            data = (frequency, width, height, jpeg)
            camera = self.cam_mgr.getCameraById(cam_id)
            logging.debug("Received VV_REQ_IMG message from conn:%s" % conn_id)
            if camera and not camera.hasSession():
                session = self.activeSessions[conn_id]
                session.addCamera(cam_id)
                camera.setSession(session, VP_BASIC, self.ip, self.port, data)

        else:
            if conn_id in self.activeSessions:
                self.activeSessions[conn_id].newMessage(message_type, packet)

    def newVPSession(self, conn, type, pipeline, conn_id):

        if type == VP_ADVANCED:
            camera_type = -1
            if pipeline == STATIC_PIPELINE:
                camera_type = STATIC_CAMERA  ## Change this to use a different static camera class
            elif pipeline == PTZ_PIPELINE:
                camera_type = ACTIVE_CAMERA
            if camera_type != -1:
                cam = self.cam_mgr.getAvailableCamera(camera_type)
                if cam:
                    session = VPSession(conn_id, conn, self, VP, pipeline)
                    session.addCamera(cam.getId())
                    self.activeSessions[conn_id] = session
                    message = eVV_VP_ACK_OK(self.ip, self.port, cam.getId())
                    logging.debug("Sent VV_VP_ACK_OK message to conn:%s" %
                                  conn_id)
                    self.sendMessage(message, conn)
                    cam.setSession(session, type, self.ip, self.port)

                else:
                    message = eVV_VP_ACK_FAILED(self.ip, self.port)
                    logging.debug("Sent VV_VP_ACK_FAILED message to conn:%s" %
                                  conn_id)
                    self.sendMessage(message, conn)
        else:
            message = eVV_VP_ACK_FAILED(self.ip, self.port)
            logging.debug("Sent VV_VP_ACK_FAILED message to conn:%s" % conn_id)
            self.sendMessage(message, conn)

    def newSyncSession(self, conn, conn_id, vv_id):
        session = SyncSession(conn_id, conn, self, SYNC)
        self.sync.setSession(session, vv_id, self.ip, self.port)
        self.activeSessions[conn_id] = session
        message = eVV_SYNC_ACK(self.ip, self.port, vv_id)
        logging.debug("Sent VV_SYNC_ACK message to conn:%s" % conn_id)
        self.sendMessage(message, conn)

    def sendMessage(self, message, conn):
        self.cWriter.send(message, conn)

    def disconnection_polling(self, taskdata):
        if (self.cManager.resetConnectionAvailable()):
            connectionPointer = PointerToConnection()
            self.cManager.getResetConnection(connectionPointer)
            lostConnection = connectionPointer.p()
            for session in self.activeSessions.values():
                if session.conn == lostConnection:
                    logging.info("Lost Connection from ip:%s, conn:%s" %
                                 (session.client_address, session.conn_id))
                    conn_id = session.conn_id
                    if session.getSessionType() == VP:
                        cameras = session.getCameras()
                        for cam_id in cameras:
                            camera = self.cam_mgr.getCameraById(cam_id)
                            camera.clearSession()

                    del self.activeSessions[conn_id]
                    del self.connection_map[conn_id]
                    break
            self.cManager.closeConnection(lostConnection)
        return Task.cont

    def toggleInfo(self):
        if self.showing_info:
            self.info_label.hide()
            self.showing_info = False
        else:
            self.info_label.show()
            self.showing_info = True

    def exit(self):
        for connection in self.connection_map.values():
            self.cReader.removeConnection(connection)
        self.cManager.closeConnection(self.tcpSocket)
        self.tcpSocket.getSocket().Close()
Exemplo n.º 3
0
class Server:
    def __init__(self, port, backlog=1000, compress=False):
        self.port = port
        self.backlog = backlog
        self.compress = compress

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.activeConnections = []  # We'll want to keep track of these later

        self.connect(self.port, self.backlog)
        self.startPolling()

    def connect(self, port, backlog=1000):
        # Bind to our socket
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener.addConnection(self.tcpSocket)

    def disconnect(self, port, backlog=1000):
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cManager.closeConnection(self.tcpSocket)
        taskMgr.remove("serverListenTask")
        taskMgr.remove("serverDisconnectTask")

    def startPolling(self):
        taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
        taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask", -39)

    def tskListenerPolling(self, task):
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConnection = PointerToConnection()

            if self.cListener.getNewConnection(rendezvous, netAddress,
                                               newConnection):
                newConnection = newConnection.p()
                self.activeConnections.append(
                    newConnection)  # Remember connection
                self.cReader.addConnection(
                    newConnection)  # Begin reading connection
        return Task.cont

    def tskDisconnectPolling(self, task):
        while self.cManager.resetConnectionAvailable() == True:
            connPointer = PointerToConnection()
            self.cManager.getResetConnection(connPointer)
            connection = connPointer.p()

            # Remove the connection we just found to be "reset" or "disconnected"
            self.cReader.removeConnection(connection)

            # Loop through the activeConnections till we find the connection we just deleted
            # and remove it from our activeConnections list
            for c in range(0, len(self.activeConnections)):
                if self.activeConnections[c] == connection:
                    del self.activeConnections[c]
                    break

        return Task.cont

    def broadcastData(self, data):
        # Broadcast data out to all activeConnections
        for con in self.activeConnections:
            self.sendData(data, con)

    def processData(self, netDatagram):
        myIterator = PyDatagramIterator(netDatagram)
        return self.decode(myIterator.getString())

    def getClients(self):
        # return a list of all activeConnections
        return self.activeConnections

    def encode(self, data, compress=False):
        # encode(and possibly compress) the data with rencode
        return rencode.dumps(data, compress)

    def decode(self, data):
        # decode(and possibly decompress) the data with rencode
        return rencode.loads(data)

    def sendData(self, data, con):
        myPyDatagram = PyDatagram()
        myPyDatagram.addString(self.encode(data, self.compress))
        self.cWriter.send(myPyDatagram, con)

    def getData(self):
        data = []
        while self.cReader.dataAvailable():
            datagram = NetDatagram(
            )  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                data.append(self.processData(datagram))
        return data
Exemplo n.º 4
0
class Server(DirectObject): 
    def __init__( self ): 
        self.port = 9099 
        self.portStatus = "Closed" 
        self.host = "localhost" 
        self.backlog = 1000 
        self.Connections = {} 
        # basic configuration variables that are used by most of the 
        # other functions in this class 

        self.StartConnectionManager() 
        # manages the connection manager 
        
        self.DisplayServerStatus() 
        # output a status box to the console which tells you the port 
        # and any connections currently connected to your server 
        
    def DisplayServerStatusTASK(self, task): 
        # all this does is periodically load the status function below 
        # add a task to display it every 30 seconds while you are doing 
        # any new coding 
        self.DisplayServerStatus() 
        return Task.again 
    
    def DisplayServerStatus(self): 
        print "\n----------------------------------------------------------------------------\n" 
        print "SERVER STATUS:\n\n" 
        print "Connection Manager Port: " + str(self.port)  + " [" + str(self.portStatus) + "]" 
        for k, v in self.Connections.iteritems(): 
            print "Connection " + k 

    ################################################################## 
    #              TCP Networking Functions and Tasks 
    ################################################################## 
        
    def StartConnectionManager(self): 
        # this function creates a connection manager, and then 
        # creates a bunch of tasks to handle connections 
        # that connect to the server 
        self.cManager = QueuedConnectionManager() 
        self.cListener = QueuedConnectionListener(self.cManager, 0) 
        self.cReader = QueuedConnectionReader(self.cManager, 0) 
        self.cWriter = ConnectionWriter(self.cManager,0) 
        self.tcpSocket = self.cManager.openTCPServerRendezvous(self.port,self.backlog)
        self.cListener.addConnection(self.tcpSocket) 
        self.portStatus = "Open" 
        taskMgr.add(self.ConnectionManagerTASK_Listen_For_Connections,"Listening for Connections",-39) 
        # This task listens for new connections 
        taskMgr.add(self.ConnectionManagerTASK_Listen_For_Datagrams,"Listening for Datagrams",-40) 
        # This task listens for new datagrams 
        taskMgr.add(self.ConnectionManagerTASK_Check_For_Dropped_Connections,"Listening for Disconnections",-41) 
        # This task listens for disconnections 
        
    def ConnectionManagerTASK_Listen_For_Connections(self, task): 
        if(self.portStatus == "Open"): 
        # This exists in case you want to add a feature to disable your 
        # login server for some reason.  You can just put code in somewhere 
        # to set portStatus = 'closed' and your server will not 
        # accept any new connections 
            if self.cListener.newConnectionAvailable(): 
                print "CONNECTION" 
                rendezvous = PointerToConnection() 
                netAddress = NetAddress() 
                newConnection = PointerToConnection() 
                if self.cListener.getNewConnection(rendezvous,netAddress,newConnection): 
                    newConnection = newConnection.p() 
                    self.Connections[str(newConnection.this)] = rendezvous 
                    # all connections are stored in the self.Connections 
                    # dictionary, which you can use as a way to assign 
                    # unique identifiers to each connection, making 
                    # it easy to send messages out 
                    self.cReader.addConnection(newConnection)    
                    print "\nSOMEBODY CONNECTED" 
                    print "IP Address: " + str(newConnection.getAddress()) 
                    print "Connection ID: " + str(newConnection.this) 
                    print "\n" 
                    # you can delete this, I've left it in for debugging 
                    # purposes 
                    self.DisplayServerStatus()                
                    # this fucntion just outputs the port and 
                    # current connections, useful for debugging purposes 
        return Task.cont  

    def ConnectionManagerTASK_Listen_For_Datagrams(self, task): 
        if self.cReader.dataAvailable(): 
            datagram=NetDatagram()  
            if self.cReader.getData(datagram): 
                print "\nDatagram received, sending response" 
                myResponse = PyDatagram() 
                myResponse.addString("GOT YER MESSAGE") 
                self.cWriter.send(myResponse, datagram.getConnection()) 
                # this was just testing some code, but the server will 
                # automatically return a 'GOT YER MESSAGE' datagram 
                # to any connection that sends a datagram to it 
                # this is where you add a processing function here 
                #myProcessDataFunction(datagram) 
        return Task.cont 

    def ConnectionManagerTASK_Check_For_Dropped_Connections(self, task): 
        # if a connection has disappeared, this just does some house 
        # keeping to officially close the connection on the server, 
        # if you don't have this task the server will lose track 
        # of how many people are actually connected to you 
        if(self.cManager.resetConnectionAvailable()): 
            connectionPointer = PointerToConnection() 
            self.cManager.getResetConnection(connectionPointer) 
            lostConnection = connectionPointer.p() 
            # the above pulls information on the connection that was lost 
            print "\nSOMEBODY DISCONNECTED" 
            print "IP Address: " + str(lostConnection.getAddress()) 
            print "ConnectionID: " + str(lostConnection.this) 
            print "\n" 
            del self.Connections[str(lostConnection.this)] 
            # remove the connection from the dictionary 
            self.cManager.closeConnection(lostConnection) 
            # kills the connection on the server 
            self.DisplayServerStatus() 
        return Task.cont 
Exemplo n.º 5
0
class Client:
    def __init__(self, showbase, host, port, timeout=3000, compress=False):
        self.showbase = showbase
        self.host = host
        self.port = port
        self.timeout = timeout
        self.compress = compress

        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        # By default, we are not connected
        self.connected = False

        self.passedData = []

        self.connect(self.host, self.port, self.timeout)

        self.startPolling()

    def startPolling(self):
        self.showbase.taskMgr.add(self.tskDisconnectPolling,
                                  "clientDisconnectTask", -39)

    def connect(self, host, port, timeout=3000):
        # Connect to our host's socket
        self.myConnection = self.cManager.openTCPClientConnection(
            host, port, timeout)
        if self.myConnection:
            self.cReader.addConnection(
                self.myConnection)  # receive messages from server
            self.connected = True  # Let us know that we're connected

    def getConnected(self):
        # Check whether we are connected or not
        return self.connected

    def tskDisconnectPolling(self, task):
        while self.cManager.resetConnectionAvailable() == True:
            connPointer = PointerToConnection()
            self.cManager.getResetConnection(connPointer)
            connection = connPointer.p()

            # Remove the connection we just found to be "reset" or "disconnected"
            self.cReader.removeConnection(connection)

            # Let us know that we are not connected
            self.connected = False

        return Task.cont

    def processData(self, netDatagram):
        myIterator = PyDatagramIterator(netDatagram)
        return self.decode(myIterator.getString())

    def encode(self, data, compress=False):
        # encode(and possibly compress) the data with rencode
        return rencode.dumps(data, compress)

    def decode(self, data):
        # decode(and possibly decompress) the data with rencode
        return rencode.loads(data)

    def sendData(self, data):
        myPyDatagram = PyDatagram()
        myPyDatagram.addString(self.encode(data, self.compress))
        self.cWriter.send(myPyDatagram, self.myConnection)

    def passData(self, data):
        self.passedData.append(data)

    def getData(self):
        data = []
        for passed in self.passedData:
            data.append(passed)
            self.passedData.remove(passed)
        while self.cReader.dataAvailable():
            datagram = NetDatagram()
            if self.cReader.getData(datagram):
                data.append(self.processData(datagram))
        return data
Exemplo n.º 6
0
class Client:
    def __init__(self, host, port, timeout=3000, compress=False):
        self.host = host
        self.port = port
        self.timeout = timeout
        self.compress = compress

        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        # By default, we are not connected
        self.connected = False

        self.connect(self.host, self.port, self.timeout)
        self.startPolling()

    def connect(self, host, port, timeout=3000):
        # Connect to our host's socket
        self.myConnection = self.cManager.openTCPClientConnection(host, port, timeout)
        if self.myConnection:
            self.cReader.addConnection(self.myConnection)  # receive messages from server
            self.connected = True  # Let us know that we're connected

    def startPolling(self):
        taskMgr.add(self.tskDisconnectPolling, "clientDisconnectTask", -39)

    def tskDisconnectPolling(self, task):
        while self.cManager.resetConnectionAvailable() == True:
            connPointer = PointerToConnection()
            self.cManager.getResetConnection(connPointer)
            connection = connPointer.p()

            # Remove the connection we just found to be "reset" or "disconnected"
            self.cReader.removeConnection(connection)

            # Let us know that we are not connected
            self.connected = False

        return Task.cont

    def processData(self, netDatagram):
        myIterator = PyDatagramIterator(netDatagram)
        return self.decode(myIterator.getString())

    def getConnected(self):
        # Check whether we are connected or not
        return self.connected

    def encode(self, data, compress=False):
        # encode(and possibly compress) the data with rencode
        return rencode.dumps(data, compress)

    def decode(self, data):
        # decode(and possibly decompress) the data with rencode
        return rencode.loads(data)

    def sendData(self, data):
        myPyDatagram = PyDatagram()
        myPyDatagram.addString(self.encode(data, self.compress))
        self.cWriter.send(myPyDatagram, self.myConnection)

    def getData(self):
        data = []
        while self.cReader.dataAvailable():
            datagram = NetDatagram()  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                data.append(self.processData(datagram))
        return data
Exemplo n.º 7
0
class LoginServer:
	def __init__(self, port, backlog=1000, compress=False):
		self.port = port
		self.backlog = backlog
		self.compress = compress

		self.cManager = QueuedConnectionManager()
		self.cListener = QueuedConnectionListener(self.cManager, 0)
		self.cReader = QueuedConnectionReader(self.cManager, 0)
		self.cWriter = ConnectionWriter(self.cManager,0)
		
		self.db = DataBase()
		# This is for pre-login
		self.tempConnections = []
		# This is for authed clients
		self.activeConnections = []
		
		# Temp user dict
		self.clients={}
		
		self.connect(self.port, self.backlog)
		self.startPolling()

	def connect(self, port, backlog=1000):
		# Bind to our socket
		tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
		self.cListener.addConnection(tcpSocket)

	def startPolling(self):
		taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
		taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask", -39)

	def tskListenerPolling(self, task):
		if self.cListener.newConnectionAvailable():
			rendezvous = PointerToConnection()
			netAddress = NetAddress()
			newConnection = PointerToConnection()

			if self.cListener.getNewConnection(rendezvous, netAddress, newConnection):
				newConnection = newConnection.p()
				self.tempConnections.append(newConnection) # Lets add it to a temp list first.
				self.cReader.addConnection(newConnection)     # Begin reading connection
				
				# Make the temp place holder then add to temp, under dataget check the temp list, if something ther do
				# auth and then add to the active
		return Task.cont

	def tskDisconnectPolling(self, task):
		while self.cManager.resetConnectionAvailable() == True:
			print "disconnect"
			connPointer = PointerToConnection()
			self.cManager.getResetConnection(connPointer)
			connection = connPointer.p()
			
			# Remove the connection we just found to be "reset" or "disconnected"
			self.cReader.removeConnection(connection)
			# Remove the connection we just found to be "reset" or "disconnected"
			self.cReader.removeConnection(connection)
			for u in range(len(self.clients)):
				if self.clients[u]['connection']==connection:
					del self.clients[u]
					break
			
			# Loop through the activeConnections till we find the connection we just deleted
			# and remove it from our activeConnections list
			for c in range(0, len(self.activeConnections)):
				if self.activeConnections[c] == connection:
					del self.activeConnections[c]
					break
					
		return Task.cont

	def broadcastData(self, data):
		# Broadcast data out to all activeConnections
		for con in self.activeConnections:
			self.sendData(data, con)

	def processData(self, netDatagram):
		myIterator = PyDatagramIterator(netDatagram)
		return self.decode(myIterator.getString())

	def getClients(self):
		# return a list of all activeConnections
		return self.activeConnections

	def encode(self, data, compress=False):
		# encode(and possibly compress) the data with rencode
		return rencode.dumps(data, compress)

	def decode(self, data):
		# decode(and possibly decompress) the data with rencode
		return rencode.loads(data)

	def sendData(self, data, con):
		myPyDatagram = PyDatagram()
		myPyDatagram.addString(self.encode(data, self.compress))
		self.cWriter.send(myPyDatagram, con)
		
	# This will check and do the logins.
	def auth(self, datagram): 
		# If in login state.
		clientIp = datagram.getAddress() # This is the ip :P
		clientCon = datagram.getConnection() # This is the connection data. used to send the shit.
		package=self.processData(datagram)
		print "SERVER: ",package
		valid_packet=False
		if len(package)==2:
			# if login request is send reply
			# Should add a checker like in the db something like isLogged(0 or 1)
			# If found then say no for client
			user_found=False
			if package[0]=='login_request':
				valid_packet=True
				print "Try login"
				for u in range(len(self.clients)):
					if self.clients[u]['name']==package[1][0]:
						print "User already exists"
						user_found=True
						data = {}
						data[0] = "error"
						data[1] = "User already logged in"
						self.sendData(data,clientCon)
						break
						# send something back to the client saying to change username
				if not user_found:
					username=package[1][0]
					password=package[1][1]
					self.db.Client_getLogin(username, password)
					if self.db.login_valid:
						# Add the user
						new_user={}
						new_user['name']=package[1][0]
						new_user['connection']=clientCon
						new_user['ready']=False
						new_user['new_dest']=False
						new_user['new_spell']=False
						self.clients[len(self.clients)]=new_user
							# Send back the valid check.
						data={}
						data[0]='login_valid' # If client gets this the client should switch to main_menu.
						data[1]={}
						data[1][0]=self.db.status
						data[1][1]=len(self.clients)-1 # This is part of the old 'which' packet
						self.sendData(data, clientCon)
					
						# Move client to the self.activeConnections list.
						self.activeConnections.append(clientCon)
						print "HERE IS ACTIVE: ", self.activeConnections
						self.tempConnections.remove(clientCon)
						print "HERE IS TEMP", self.tempConnections
					
				else:
					status = self.db.status
					data={}
					data[0]='db_reply'
					data[1]=status
					self.sendData(data, clientCon)
			if not valid_packet:
				data = {}
				data[0] = "error"
				data[1] = "Wrong Packet"
				self.sendData(data, clientCon)
				print "Login Packet not correct"
				
		else:
			print "Data in packet wrong size"

	def getData(self):
		data = []
		while self.cReader.dataAvailable():
			datagram = NetDatagram()  # catch the incoming data in this instance
			# Check the return value; if we were threaded, someone else could have
			# snagged this data before we did
			if self.cReader.getData(datagram):
				
				if datagram.getConnection() in self.tempConnections:
					print "Check Auth!"
					self.auth(datagram)
					print "Auth Done!"
					# in auth def or after the connection will be moved to self.activeConnections
					# and then removed from the temp list
					break
				# Check if the data rechieved is from a valid client.
				elif datagram.getConnection() in self.activeConnections:
					appendage={}
					appendage[0]=self.processData(datagram)
					appendage[1]=datagram.getConnection()
					data.append(appendage)
					
				
		return data
Exemplo n.º 8
0
class Server:
    def __init__(self, port, backlog=1000, compress=False):
        self.port = port
        self.backlog = backlog
        self.compress = compress
        
        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager,0)
        
        self.activeConnections = [] # We'll want to keep track of these later
        
        self.connect(self.port, self.backlog)
        self.startPolling()

    def connect(self, port, backlog=1000):
        # Bind to our socket
        tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener.addConnection(tcpSocket)

    def startPolling(self):
        taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
        taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask", -39)
        
    def tskListenerPolling(self, task):
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConnection = PointerToConnection()
        
            if self.cListener.getNewConnection(rendezvous, netAddress, newConnection):
                newConnection = newConnection.p()
                self.activeConnections.append(newConnection) # Remember connection
                self.cReader.addConnection(newConnection)     # Begin reading connection
        return Task.cont
    
    def tskDisconnectPolling(self, task):
        while self.cManager.resetConnectionAvailable() == True:
            connPointer = PointerToConnection()
            self.cManager.getResetConnection(connPointer)
            connection = connPointer.p()
            
            # Remove the connection we just found to be "reset" or "disconnected"
            self.cReader.removeConnection(connection)
            
            # Loop through the activeConnections till we find the connection we just deleted
            # and remove it from our activeConnections list
            for c in range(0, len(self.activeConnections)):
                if self.activeConnections[c] == connection:
                    del self.activeConnections[c]
                    break
                    
        return Task.cont
    
    def broadcastData(self, data):
        # Broadcast data out to all activeConnections
        for con in self.activeConnections:
            self.sendData(data, con)
        
    def processData(self, netDatagram):
        myIterator = PyDatagramIterator(netDatagram)
        return self.decode(myIterator.getString())
        
    def getClients(self):
        # return a list of all activeConnections
        return self.activeConnections
        
    def encode(self, data, compress=False):
        # encode(and possibly compress) the data with rencode
        return rencode.dumps(data, compress)
        
    def decode(self, data):
        # decode(and possibly decompress) the data with rencode
        return rencode.loads(data)
        
    def sendData(self, data, con):
        myPyDatagram = PyDatagram()
        myPyDatagram.addString(self.encode(data, self.compress))
        self.cWriter.send(myPyDatagram, con)
    
    def getData(self):
        data = []
        while self.cReader.dataAvailable():
            datagram = NetDatagram()  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                data.append(self.processData(datagram))
        return data
Exemplo n.º 9
0
class LoginServer(ShowBase):
    def __init__(self, port, backlog=1000, compress=False):
        ShowBase.__init__(self)

        self.compress = compress

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.clientdb = ClientDataBase()
        if not self.clientdb.connected:
            self.clientdb = None
            print 'Login Server failed to start...'
        else:
            # This is for pre-login
            self.tempConnections = []

            # This is for authed clients
            self.activeClients = []
            # This is for authed servers
            self.activeServers = []
            # This is for authed chat servers
            self.activeChats = []

            self.connect(port, backlog)
            self.startPolling()

            self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')

            print 'Login Server operating...'

    def connect(self, port, backlog=1000):
        # Bind to our socket
        tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener.addConnection(tcpSocket)

    def startPolling(self):
        self.taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
        self.taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask",
                         -39)

    def tskListenerPolling(self, task):
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConnection = PointerToConnection()
            if self.cListener.getNewConnection(rendezvous, netAddress,
                                               newConnection):
                newConnection = newConnection.p()
                self.tempConnections.append(newConnection)
                self.cReader.addConnection(newConnection)
        return Task.cont

    def tskDisconnectPolling(self, task):
        while self.cManager.resetConnectionAvailable() == True:
            connPointer = PointerToConnection()
            self.cManager.getResetConnection(connPointer)
            connection = connPointer.p()

            # Remove the connection
            self.cReader.removeConnection(connection)
            # Check for if it was a client
            for client in self.activeClients:
                if client.connection == connection:
                    print 'removing client'
                    self.activeClients.remove(client)
                    break
            # then check servers
            for server in self.activeServers:
                if server.connection == connection:
                    self.activeServers.remove(server)
                    break
            # then check servers
            for chat in self.activeChats:
                if chat.connection == connection:
                    self.activeChats.remove(chat)
                    break

        return Task.cont

    def processData(self, netDatagram):
        myIterator = PyDatagramIterator(netDatagram)
        return self.decode(myIterator.getString())

    def encode(self, data, compress=False):
        # encode(and possibly compress) the data with rencode
        return rencode.dumps(data, compress)

    def decode(self, data):
        # decode(and possibly decompress) the data with rencode
        return rencode.loads(data)

    def sendData(self, data, con):
        myPyDatagram = PyDatagram()
        myPyDatagram.addString(self.encode(data, self.compress))
        self.cWriter.send(myPyDatagram, con)

    # This will check and do the logins.
    def auth(self, datagram):
        # If in login state.
        con = datagram.getConnection()
        package = self.processData(datagram)
        if len(package) == 2:
            if package[0] == 'create':
                success, result = self.clientdb.addClient(
                    package[1][0], package[1][1])
                if success:
                    self.sendData(('createSuccess', result), con)
                else:
                    self.sendData(('createFailed', result), con)
                return False
            if package[0] == 'client':
                userFound = False
                for client in self.activeClients:
                    if client.name == package[1][0]:
                        userFound = True
                        self.sendData(('loginFailed', 'logged'), con)
                        break
                if not userFound:
                    valid, result = self.clientdb.validateClient(
                        package[1][0], package[1][1])
                    if valid:
                        self.activeClients.append(Client(package[1][0], con))
                        self.sendData(('loginValid', result), con)
                        return True
                    else:
                        self.sendData(('loginFailed', result), con)
                        return False
            # if server add it to the list of current active servers
            if package[0] == 'server':
                self.activeServers.append(Server(package[1], con))
                return True
            # if server add it to the list of current active servers
            if package[0] == 'chat':
                self.activeChats.append(Chat(package[1], con))
                return True

    def getData(self):
        data = []
        while self.cReader.dataAvailable():
            datagram = NetDatagram()
            if self.cReader.getData(datagram):
                if datagram.getConnection() in self.tempConnections:
                    if self.auth(datagram):
                        self.tempConnections.remove(datagram.getConnection())
                    continue
                # Check if the data recieved is from a valid client.
                for client in self.activeClients:
                    if datagram.getConnection() == client.connection:
                        data.append(
                            ('client', self.processData(datagram), client))
                        break
                # Check if the data recieved is from a valid server.
                for server in self.activeServers:
                    if datagram.getConnection() == server.connection:
                        data.append(
                            ('server', self.processData(datagram), server))
                        break
                # Check if the data recieved is from a valid chat.
                for chat in self.activeChats:
                    if datagram.getConnection() == chat.connection:
                        data.append(('chat', self.processData(datagram), chat))
                        break
        return data

    # handles new joining clients and updates all clients of chats and readystatus of players
    def lobbyLoop(self, task):
        # if in lobby state
        temp = self.getData()
        if temp != []:
            for package in temp:
                # handle client incoming packages here
                if package[0] == 'client':
                    # This is where packages will come after clients connect to the server
                    # will be things like requesting available servers and chat servers
                    if package[1] == 'server_query':
                        for server in self.activeServers:
                            if server.state == 'lobby':
                                self.sendData(
                                    ('server',
                                     (server.name,
                                      str(server.connection.getAddress()))),
                                    package[2].connection)
                        self.sendData(('final', 'No more servers'),
                                      package[2].connection)
                # handle server incoming packages here
                elif package[0] == 'server':
                    # auth
                    # game state change
                    if len(package[1]) == 2:
                        if package[1][0] == 'auth':
                            clientAuth = False
                            print 'Attempting Authentication on: ', package[1][
                                1]
                            for client in self.activeClients:
                                if client.name == package[1][1]:
                                    clientAuth = True
                                    break
                            if clientAuth:
                                self.sendData(('auth', client.name),
                                              package[2].connection)
                            else:
                                self.sendData(('fail', package[1][1]),
                                              package[2].connection)
                        elif package[1][0] == 'state':
                            package[2].state = package[1][1]
                # handle chat server incoming packages here
                elif package[0] == 'chat':
                    print 'Authorized chat server sent package'
                    # handle packages from the chat servers
                    # like making public/private
                    # authing clients
        return task.again
Exemplo n.º 10
0
class MiniServer:

    def __init__(self, host, port, channel, serverType):
        self.port = port
        self.host = host
        self.channel = channel
        self.serverType = serverType
        self.Connections = {}
        self.startConnectionMgr()
        self.locked = 0
        #base.taskMgr.add(self.displayServerStatusTask, "displayServerStatus")
        return

    def connectToServer(self, port):
        # Connect our MiniServer to the main server.
        self.serverConnection = self.cMgr.openTCPClientConnection(self.host,
                            port, 5000)
        if self.serverConnection:
            self.cReader.addConnection(self.serverConnection)
            self.handleConnected()

    def handleConnected(self):
        self.registerChannel()

    def registerChannel(self):
        dg = PyDatagram()
        dg.addServerControlHeader(CONTROL_ADD_CHANNEL)
        dg.addChannel(self.channel)
        self.cWriter.send(dg, self.serverConnection)
        print "Registered channel: " + str(self.channel)

    def setLocked(self, value):
        if value:
            self.locked = 1
        elif not value:
            self.locked = 0

    def displayServerStatusTask(self, task):
        self.displayServerStatus()
        task.delayTime = 30
        return Task.again

    def displayServerStatus(self):
        print "-----------------------------------"
        print "Server Status..."
        print "Host: %s" % self.host
        print "Port: %s" % self.port
        print "Number of active connections: %s" % len(self.Connections)

    def startConnectionMgr(self):
        self.cMgr = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cMgr, 0)
        self.cReader = QueuedConnectionReader(self.cMgr, 0)
        self.cWriter = ConnectionWriter(self.cMgr, 0)
        self.tcpSocket = self.cMgr.openTCPServerRendezvous('', self.port, 10)
        self.cListener.addConnection(self.tcpSocket)
        taskMgr.add(self.listenerPoll, "listenForConnections", -39)
        taskMgr.add(self.datagramPoll, "listenForDatagrams", -40)
        taskMgr.add(self.disconnectionPoll, "listenForDisconnections", -41)
        print "%s server started." % self.serverType.capitalize()

    def listenerPoll(self, task):
        """ Listen for connections. """
        if not self.locked:
            if self.cListener.newConnectionAvailable():
                print "-----------------------------------"
                print "New connection available..."
                rendezvous = PointerToConnection()
                netAddress = NetAddress()
                newConnection = PointerToConnection()
                if self.cListener.getNewConnection(rendezvous, netAddress, newConnection):
                    newConnection = newConnection.p()
                    self.Connections[str(newConnection.this)] = rendezvous
                    self.cReader.addConnection(newConnection)
                    print "IP Address: %s" % newConnection.getAddress()
                    print "ConnectionID: %s" % newConnection.this
                    self.displayServerStatus()
                    #if self.__class__.__name__ == 'LoginServer':
                     #   self.sendServerMessage('ciac',
                      #                         newConnection)
        return Task.cont

    def datagramPoll(self, task):
        if self.cReader.dataAvailable():
            datagram = NetDatagram()
            if self.cReader.getData(datagram):
                self.handleDatagram(datagram)
        return Task.cont

    def disconnectionPoll(self, task):
        if self.cMgr.resetConnectionAvailable():
            connectionPointer = PointerToConnection()
            self.cMgr.getResetConnection(connectionPointer)
            lostConnection = connectionPointer.p()
            print "-----------------------------------"
            print "Farewell connection..."
            print "IP Address: %s" % lostConnection.getAddress()
            print "ConnectionID: %s" % lostConnection.this
            del self.Connections[str(lostConnection.this)]
            self.cMgr.closeConnection(lostConnection)
            self.displayServerStatus()
        return Task.cont
Exemplo n.º 11
0
class Server(ShowBase):
	def __init__(self):
		ShowBase.__init__(self)

		# Server Networking handling stuff
		self.compress = False

		self.cManager = QueuedConnectionManager()
		self.cListener = QueuedConnectionListener(self.cManager, 0)
		self.cReader = QueuedConnectionReader(self.cManager, 0)
		self.cWriter = ConnectionWriter(self.cManager, 0)

		self.tempConnections = []
		self.unauthenticatedUsers = []
		self.users = []

		self.passedData = []

		self.connect(9099, 1000)
		self.startPolling()

		self.attemptAuthentication()
		
		self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')

	def connect(self, port, backlog = 1000):
		# Bind to our socket
		tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
		self.cListener.addConnection(tcpSocket)

	def startPolling(self):
		self.taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
		self.taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask", -39)

	def tskListenerPolling(self, task):
		if self.cListener.newConnectionAvailable():
			rendezvous = PointerToConnection()
			netAddress = NetAddress()
			newConnection = PointerToConnection()

			if self.cListener.getNewConnection(rendezvous, netAddress, newConnection):
				newConnection = newConnection.p()
				newConnection.setNoDelay(True)
				self.tempConnections.append(newConnection)	# Remember connection
				self.cReader.addConnection(newConnection)	# Begin reading connection
		return Task.cont

	def tskDisconnectPolling(self, task):
		while self.cManager.resetConnectionAvailable() == True:
			connPointer = PointerToConnection()
			self.cManager.getResetConnection(connPointer)
			connection = connPointer.p()
			
			# Remove the connection we just found to be "reset" or "disconnected"
			self.cReader.removeConnection(connection)
			
			# remove from our activeConnections list
			if connection in self.tempConnections:
				self.tempConnections.remove(connection)
			for user in self.unauthenticatedUsers:
				if connection == user.connection:
					self.unauthenticatedUsers.remove(user)
			for user in self.users:
				if connection == user.connection:
					user.connection = None
					self.passData(('disconnect', user.name), None)
		
		return Task.cont

	def broadcastData(self, data):
		# Broadcast data out to all users
		for user in self.users:
			if user.connection:
				self.sendData(data, user.connection)

	def processData(self, netDatagram):
		myIterator = PyDatagramIterator(netDatagram)
		return self.decode(myIterator.getString())

	def getUsers(self):
		# return a list of all users
		return self.users

	def encode(self, data, compress = False):
		# encode(and possibly compress) the data with rencode
		return rencode.dumps(data, compress)

	def decode(self, data):
		# decode(and possibly decompress) the data with rencode
		return rencode.loads(data)

	def sendData(self, data, con):
		myPyDatagram = PyDatagram()
		myPyDatagram.addString(self.encode(data, self.compress))
		self.cWriter.send(myPyDatagram, con)

	def passData(self, data, connection):
		self.passedData.append((data, connection))

	def getData(self):
		data = []
		for passed in self.passedData:
			data.append(passed)
			self.passedData.remove(passed)
		while self.cReader.dataAvailable():
			datagram = NetDatagram()
			if self.cReader.getData(datagram):
				if datagram.getConnection() in self.tempConnections:
					self.processTempConnection(datagram)
					continue
				for authed in self.users:
					if datagram.getConnection() == authed.connection:
						data.append((self.processData(datagram), datagram.getConnection()))
		return data

	def processTempConnection(self, datagram):
		connection = datagram.getConnection()
		package = self.processData(datagram)
		if len(package) == 2:
			if package[0] == 'username':
				print 'attempting to authenticate', package[1]
				self.tempConnections.remove(connection)
				if not self.online:
					user = User(package[1], connection)
					# confirm authorization
					self.sendData(('auth', user.name), user.connection)
					self.updateClient(user)
					self.users.append(user)
				else:
					self.client.sendData(('auth', package[1]))
					self.unauthenticatedUsers.append(User(package[1], connection))

	def attemptAuthentication(self):
		config = ConfigParser.RawConfigParser()
		config.read('server.cfg')
		self.SERVER_NAME = config.get('SERVER DETAILS', 'serverName')

		config = ConfigParser.RawConfigParser()
		config.read('master.cfg')
		self.LOGIN_IP = config.get('MASTER SERVER CONNECTION', 'masterIp')
		self.LOGIN_PORT = config.getint('MASTER SERVER CONNECTION', 'masterPort')

		# Client for connecting to main server for showing exists and receiving clients
		self.client = Client(self, self.LOGIN_IP, self.LOGIN_PORT, compress = True)
		if self.client.getConnected():
			self.client.sendData(('server', self.SERVER_NAME))
			self.taskMgr.add(self.clientValidator, 'Client Validator')
			self.client.sendData(('state', 'lobby'))
			self.online = True
		else:
			# client not connected to login/auth server
			print 'Could not connect to Authentication Server.'
			print 'Server is not in online mode. No Authentication will happen for clients.'
			print 'Restart Server to attempt to connect to Authentication Server.'
			self.client = None
			self.online = False

	def clientValidator(self, task):
		temp = self.client.getData()
		for package in temp:
			if len(package) == 2:
				if package[0] == 'auth':
					print 'User authenticated: ', package[1]
					for user in self.unauthenticatedUsers:
						if user.name == package[1]:
							# confirm authorization
							self.sendData(('auth', user.name), user.connection)
							# send all required data to user
							self.updateClient(user)
							# all authenticated users
							self.users.append(user)
							self.unauthenticatedUsers.remove(user)
							print 'confirmation sent to ', package[1]
							break
				elif package[0] == 'fail':
					print 'User failed authentication: ', package[1]
					for user in self.unauthenticatedUsers:
						if user.name == package[1]:
							self.sendData(('fail', user.name), user.connection)
							self.unauthenticatedUsers.remove(user)
							break
		return task.again

	def updateClient(self, user):
		for existing in self.users:
			if existing.name != user.name:
				self.sendData(('client', existing.name), user.connection)
				self.sendData(('ready', (existing.name, existing.ready)), user.connection)
				if existing.connection:
					self.sendData(('client', user.name), existing.connection)
		self.sendData(('client', user.name), user.connection)

	def lobbyLoop(self, task):
		temp = self.getData()
		for package in temp:
			if len(package) == 2:
				print "Received: ", str(package)
				packet = package[0]
				connection = package[1]
				if len(packet) == 2:
					# check to make sure connection has username
					for user in self.users:
						if user.connection == connection:
							# if chat packet
							if packet[0] == 'chat':
								print 'Chat: ', packet[1]
								# Broadcast data to all clients ("username: message")
								self.broadcastData(('chat', (user.name, packet[1])))
							# else if ready packet
							elif packet[0] == 'ready':
								print user.name, ' changed readyness!'
								user.ready = packet[1]
								self.broadcastData(('ready', (user.name, user.ready)))
							# else if disconnect packet
							elif packet[0] == 'disconnect':
								print user.name, ' is disconnecting!'
								self.users.remove(user)
								self.broadcastData(('disconnect', user.name))
							# break out of for loop
							break
		# if all players are ready and there is X of them
		gameReady = True
		# if there is any clients connected
		if self.getUsers() == []:
			gameReady = False
		for user in self.users:
			if not user.ready:
				gameReady = False
		if gameReady:
			self.prepareGame()
			return task.done
		return task.again
		
	def prepareGame(self):
		if self.camera:
			# Disable Mouse Control for camera
			self.disableMouse()
			
			self.camera.setPos(0, 0, 500)
			self.camera.lookAt(0, 0, 0)

		self.gameData = GameData(True)
		
		# game data
		self.broadcastData(('gamedata', self.gameData.packageData()))
		self.broadcastData(('state', 'preround'))
		if self.online:
			self.client.sendData(('state', 'preround'))
		print "Preparing Game"
		self.gameTime = 0
		self.tick = 0

		usersData = []
		for user in self.users:
			usersData.append(user.gameData)
		self.game = Game(self, usersData, self.gameData)
		self.taskMgr.doMethodLater(0.5, self.roundReadyLoop, 'Game Loop')
		print "Round ready State"
		
	def roundReadyLoop(self, task):
		temp = self.getData()
		for package in temp:
			if len(package) == 2:
				print "Received: ", str(package)
				if len(package[0]) == 2:
					for user in self.users:
						if user.connection == package[1]:
							if package[0][0] == 'round':
								if package[0][1] == 'sync':
									user.sync = True
		# if all players are ready and there is X of them
		roundReady = True
		# if there is any clients connected
		for user in self.users:
			if user.sync == False:
				roundReady = False
		if roundReady:
			self.taskMgr.doMethodLater(2.5, self.gameLoop, 'Game Loop')
			print "Game State"
			return task.done
		return task.again
	
	def gameLoop(self, task):
		# process incoming packages
		temp = self.getData()
		for package in temp:
			if len(package) == 2:
				# check to make sure connection has username
				for user in self.users:
					if user.connection == package[1]:
						user.gameData.processUpdatePacket(package[0])
		# get frame delta time
		dt = self.taskMgr.globalClock.getDt()
		self.gameTime += dt
		# if time is less than 3 secs (countdown for determining pings of clients?)
		# tick out for clients
		while self.gameTime > gameTick:
			# update all clients with new info before saying tick
			for user in self.users:
				updates = user.gameData.makeUpdatePackets()
				for packet in updates:
					self.broadcastData((user.name, packet))
			self.broadcastData(('tick', self.tick))
			self.gameTime -= gameTick
			self.tick += 1
			# run simulation
			if not self.game.runTick(gameTick):
				print 'Game Over'
				# send to all players that game is over (they know already but whatever)
				# and send final game data/scores/etc
				for user in self.users:
					user.ready = False
				self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')
				return task.done
		return task.cont
class SocketServer():

    def __init__(self, port, virtual_world, camera_mgr, sync_session):
        self.port = port
        self.virtual_world = virtual_world
        self.cam_mgr = camera_mgr
        
        self.task_mgr = virtual_world.taskMgr
        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cReader.setRawMode(True)
        self.cWriter = ConnectionWriter(self.cManager, 1)
        self.cWriter.setRawMode(True)
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, BACKLOG)
        self.cListener.addConnection(self.tcpSocket)
        
        self.activeSessions = {}
        self.connection_map = {}
        self.set_handlers()
        
        hostname = socket.gethostname()
        a, b, address_list = socket.gethostbyname_ex(hostname)
        self.ip = address_list[0]
        logging.info("Addresses %s" % address_list)
        logging.info("Server is running on ip: %s, port: %s" 
                     %(self.ip, self.port))
        
        self.client_counter = 0
        self.read_buffer = ''
        self.read_state = 0
        self.read_body_length = 0
        self.packet = SocketPacket()
        
        controller = virtual_world.getController()
        self.sync = Sync(self.task_mgr, controller, camera_mgr, sync_session)
        self.vv_id = None
        if sync_session:
            logging.info("Waiting for Sync Client!")
        
        self.showing_info = False
        virtual_world.accept("i", self.toggleInfo)
        self.sync_session = sync_session
        self.createInfoLabel()

        atexit.register(self.exit)


    def createInfoLabel(self):

        string = self.generateInfoString()
        self.info_label = OST(string, 
                              pos=(-1.3, -0.5), 
                              fg=(1,1,1,1), 
                              bg=(0,0,0,0.7),
                              scale=0.05, 
                              align=TextNode.ALeft)
        self.info_label.hide()
    
    def generateInfoString(self,):
        string = " IP:\t%s  \n" % self.ip
        string += " PORT:\t%s \n" % self.port
        if self.sync_session:
            string += " MODE:\tSync Client\n"
            string += " VV ID:\t%s\n" % self.vv_id
        else:
            string += " MODE:\tAutomatic\n"
          
        cameras = self.cam_mgr.getCameras()
        num_cameras = len(cameras)

        for camera in cameras:
            id = camera.getId()
            type = camera.getTypeString()
            string += " Cam%s:\t%s\n" %(id, type)
        string += "\n"
        return string
    
    
    def set_handlers(self):
        self.task_mgr.add(self.connection_polling, "Poll new connections", -39)
        self.task_mgr.add(self.reader_polling, "Poll reader", -40)
        self.task_mgr.add(self.disconnection_polling, "PollDisconnections", -41)


    def connection_polling(self, taskdata):
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConn = PointerToConnection()
            if self.cListener.getNewConnection(rendezvous,netAddress, newConn):
                conn = newConn.p()
                self.cReader.addConnection(conn)     # Begin reading connection
                conn_id = self.client_counter
                logging.info("New Connection from ip:%s, conn:%s"
                             % (conn.getAddress(), conn_id))
                self.connection_map[conn_id] = conn
                self.client_counter += 1
                message = eVV_ACK_OK(self.ip, self.port, conn_id)
                self.sendMessage(message, conn)

        return Task.cont


    def reader_polling(self, taskdata):

        if self.cReader.dataAvailable():
            datagram = NetDatagram()  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                self.read_buffer = self.read_buffer + datagram.getMessage()
        while (True):
            if self.read_state == 0:
                if len(self.read_buffer) >= self.packet.header_length:
                    bytes_consumed = self.packet.header_length
                    self.packet.header = self.read_buffer[:bytes_consumed]
                    self.read_body_length = self.packet.decode_header()
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 1
                else:
                    break
            if self.read_state == 1:
                if len(self.read_buffer) >= self.read_body_length:
                    bytes_consumed = self.read_body_length
                    self.packet.data = self.read_buffer[:bytes_consumed]
                    self.packet.offset = 0        
                    self.read_body_length = 0
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 0
                    self.new_data_callback(self.packet)

                else:
                    break
        return Task.cont


    def new_data_callback(self, packet):
        packet = copy.deepcopy(packet)
        message_type = packet.get_int()
        conn_id = packet.get_int()
        if message_type == VP_SESSION:
            conn = self.connection_map[conn_id]
            type = packet.get_char()
            pipeline = packet.get_char()
            req_cam_id = packet.get_int()
            logging.debug("Received VP_SESSION message from conn:%s, " \
                          "type=%s, pipeline=%s requested camera id=%d" 
                          %(conn_id, VP_TYPE[type], PIPELINE[pipeline], req_cam_id))
            self.newVPSession(conn, type, pipeline, conn_id, req_cam_id)

        elif message_type == SYNC_SESSION:
            vv_id = packet.get_int()
            self.vv_id = vv_id
            string = self.generateInfoString()
            self.info_label.setText(string)
            conn = self.connection_map[conn_id]
            logging.debug("Received SYNC_SESSION message from conn:%s" %conn_id)
            self.newSyncSession(conn, conn_id, vv_id)
            logging.info("Sync client connected")
            
        elif message_type == VP_REQ_CAM_LIST:
            logging.debug("Received VP_REQ_CAM_LIST message from conn:%s" 
                          % conn_id) 
            cameras = self.cam_mgr.getCameras()
            pipeline = self.activeSessions[conn_id].getPipeline()
            camera_type = None
            if pipeline == STATIC_PIPELINE:
                camera_type = VP_STATIC_CAMERA
            elif pipeline == PTZ_PIPELINE:
                camera_type = VP_ACTIVE_CAMERA
            cam_list = []
            for camera in cameras:
                if camera_type == camera.getType() and not camera.hasSession():
                    cam_list.append(camera.getId())
            message = eVV_CAM_LIST(self.ip, self.port, cam_list)
            conn = self.connection_map[conn_id]
            logging.debug("Sent VV_CAM_LIST message to conn:%s" % conn_id)
            self.sendMessage(message, conn)

        elif message_type == VP_REQ_IMG:
            cam_id = packet.get_int()
            frequency = packet.get_char()
            width = packet.get_int()
            height = packet.get_int()
            jpeg = packet.get_bool()
            data = (frequency, width, height, jpeg)
            camera = self.cam_mgr.getCameraById(cam_id)
            logging.debug("Received VV_REQ_IMG message from conn:%s" % conn_id)
            if camera and not camera.hasSession():
                session = self.activeSessions[conn_id]
                session.addCamera(cam_id)
                camera.setSession(session, VP_BASIC, self.ip, self.port, data)
            
        else:
            if conn_id in self.activeSessions:
                self.activeSessions[conn_id].newMessage(message_type, packet)


    def newVPSession(self, conn, type, pipeline, conn_id, req_cam_id):

        if type == VP_ADVANCED:
            camera_type = -1
            if pipeline == STATIC_PIPELINE:
                camera_type = STATIC_CAMERA ## Change this to use a different static camera class
            elif pipeline == PTZ_PIPELINE:
                camera_type = ACTIVE_CAMERA
            if camera_type != -1:
                #cam = self.cam_mgr.getAvailableCamera(camera_type)
                cam = self.cam_mgr.getRequestedCamera(camera_type, req_cam_id)
                if cam:
                    session = VPSession(conn_id, conn, self, VP, pipeline)
                    session.addCamera(cam.getId())
                    self.activeSessions[conn_id] = session
                    message = eVV_VP_ACK_OK(self.ip, self.port, cam.getId())
                    logging.debug("Sent VV_VP_ACK_OK message to conn:%s" 
                                  % conn_id)
                    self.sendMessage(message, conn)
                    cam.setSession(session, type, self.ip, self.port)
                    
                else:
                    message = eVV_VP_ACK_FAILED(self.ip, self.port)
                    logging.debug("Sent VV_VP_ACK_FAILED message to conn:%s" 
                                  % conn_id)
                    self.sendMessage(message, conn)
        else:
            message = eVV_VP_ACK_FAILED(self.ip, self.port)
            logging.debug("Sent VV_VP_ACK_FAILED message to conn:%s" 
                          % conn_id)
            self.sendMessage(message, conn)


    def newSyncSession(self, conn, conn_id, vv_id):
        session = SyncSession(conn_id, conn, self, SYNC)
        self.sync.setSession(session, vv_id, self.ip, self.port)
        self.activeSessions[conn_id] = session
        message = eVV_SYNC_ACK(self.ip, self.port, vv_id)
        logging.debug("Sent VV_SYNC_ACK message to conn:%s" % conn_id)
        self.sendMessage(message, conn)


    def sendMessage(self, message, conn):
        self.cWriter.send(message, conn)


    def disconnection_polling(self, taskdata):
        if(self.cManager.resetConnectionAvailable()):
            connectionPointer = PointerToConnection()
            self.cManager.getResetConnection(connectionPointer)
            lostConnection = connectionPointer.p()
            for session in self.activeSessions.values():
                if session.conn == lostConnection:
                    logging.info("Lost Connection from ip:%s, conn:%s" 
                                 %(session.client_address, session.conn_id))
                    conn_id = session.conn_id
                    if session.getSessionType() == VP:
                        cameras = session.getCameras()
                        for cam_id in cameras:
                            camera = self.cam_mgr.getCameraById(cam_id)
                            camera.clearSession()
                      
                    del self.activeSessions[conn_id]
                    del self.connection_map[conn_id]
                    break
            self.cManager.closeConnection(lostConnection)
        return Task.cont
    

    def toggleInfo(self):
        if self.showing_info:
            self.info_label.hide()
            self.showing_info = False
        else:
            self.info_label.show()
            self.showing_info = True


    def exit(self):
        for connection in self.connection_map.values():
            self.cReader.removeConnection(connection)
        self.cManager.closeConnection(self.tcpSocket)
        self.tcpSocket.getSocket().Close()
Exemplo n.º 13
-1
class LoginServer(ShowBase):
	def __init__(self, port, backlog = 1000, compress = False):
		ShowBase.__init__(self)

		self.compress = compress

		self.cManager = QueuedConnectionManager()
		self.cListener = QueuedConnectionListener(self.cManager, 0)
		self.cReader = QueuedConnectionReader(self.cManager, 0)
		self.cWriter = ConnectionWriter(self.cManager,0)
		
		self.clientdb = ClientDataBase()
		if not self.clientdb.connected:
			self.clientdb = None
			print 'Login Server failed to start...'
		else:
			# This is for pre-login
			self.tempConnections = []
			
			# This is for authed clients
			self.activeClients = []
			# This is for authed servers
			self.activeServers = []
			# This is for authed chat servers
			self.activeChats = []
			
			self.connect(port, backlog)
			self.startPolling()
			
			self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')
			
			print 'Login Server operating...'

	def connect(self, port, backlog = 1000):
		# Bind to our socket
		tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
		self.cListener.addConnection(tcpSocket)

	def startPolling(self):
		self.taskMgr.add(self.tskListenerPolling, "serverListenTask", -40)
		self.taskMgr.add(self.tskDisconnectPolling, "serverDisconnectTask", -39)

	def tskListenerPolling(self, task):
		if self.cListener.newConnectionAvailable():
			rendezvous = PointerToConnection()
			netAddress = NetAddress()
			newConnection = PointerToConnection()
			if self.cListener.getNewConnection(rendezvous, netAddress, newConnection):
				newConnection = newConnection.p()
				self.tempConnections.append(newConnection)
				self.cReader.addConnection(newConnection)
		return Task.cont

	def tskDisconnectPolling(self, task):
		while self.cManager.resetConnectionAvailable() == True:
			connPointer = PointerToConnection()
			self.cManager.getResetConnection(connPointer)
			connection = connPointer.p()
			
			# Remove the connection
			self.cReader.removeConnection(connection)
			# Check for if it was a client
			for client in self.activeClients:
				if client.connection == connection:
					print 'removing client'
					self.activeClients.remove(client)
					break
			# then check servers
			for server in self.activeServers:
				if server.connection == connection:
					self.activeServers.remove(server)
					break
			# then check servers
			for chat in self.activeChats:
				if chat.connection == connection:
					self.activeChats.remove(chat)
					break
		
		return Task.cont

	def processData(self, netDatagram):
		myIterator = PyDatagramIterator(netDatagram)
		return self.decode(myIterator.getString())

	def encode(self, data, compress = False):
		# encode(and possibly compress) the data with rencode
		return rencode.dumps(data, compress)

	def decode(self, data):
		# decode(and possibly decompress) the data with rencode
		return rencode.loads(data)

	def sendData(self, data, con):
		myPyDatagram = PyDatagram()
		myPyDatagram.addString(self.encode(data, self.compress))
		self.cWriter.send(myPyDatagram, con)
		
	# This will check and do the logins.
	def auth(self, datagram): 
		# If in login state.
		con = datagram.getConnection()
		package = self.processData(datagram)
		if len(package) == 2:
			if package[0] == 'create':
				success, result = self.clientdb.addClient(package[1][0], package[1][1])
				if success:
					self.sendData(('createSuccess', result), con)
				else:
					self.sendData(('createFailed', result), con)
				return False
			if package[0] == 'client':
				userFound = False
				for client in self.activeClients:
					if client.name == package[1][0]:
						userFound = True
						self.sendData(('loginFailed', 'logged'), con)
						break
				if not userFound:
					valid, result = self.clientdb.validateClient(package[1][0], package[1][1])
					if valid:
						self.activeClients.append(Client(package[1][0], con))
						self.sendData(('loginValid', result), con)
						return True
					else:
						self.sendData(('loginFailed', result), con)
						return False
			# if server add it to the list of current active servers
			if package[0] == 'server':
				self.activeServers.append(Server(package[1], con))
				return True
			# if server add it to the list of current active servers
			if package[0] == 'chat':
				self.activeChats.append(Chat(package[1], con))
				return True

	def getData(self):
		data = []
		while self.cReader.dataAvailable():
			datagram = NetDatagram()
			if self.cReader.getData(datagram):
				if datagram.getConnection() in self.tempConnections:
					if self.auth(datagram):
						self.tempConnections.remove(datagram.getConnection())
					continue
				# Check if the data recieved is from a valid client.
				for client in self.activeClients:
					if datagram.getConnection() == client.connection:
						data.append(('client', self.processData(datagram), client))
						break
				# Check if the data recieved is from a valid server.
				for server in self.activeServers:
					if datagram.getConnection() == server.connection:
						data.append(('server', self.processData(datagram), server))
						break
				# Check if the data recieved is from a valid chat.
				for chat in self.activeChats:
					if datagram.getConnection() == chat.connection:
						data.append(('chat', self.processData(datagram), chat))
						break
		return data

	# handles new joining clients and updates all clients of chats and readystatus of players
	def lobbyLoop(self, task):
		# if in lobby state
		temp = self.getData()
		if temp != []:
			for package in temp:
				# handle client incoming packages here
				if package[0] == 'client':
					# This is where packages will come after clients connect to the server
					# will be things like requesting available servers and chat servers
					if package[1] == 'server_query':
						for server in self.activeServers:
							if server.state == 'lobby':
								self.sendData(
									('server', (server.name, str(server.connection.getAddress()))),
									package[2].connection)
						self.sendData(
							('final', 'No more servers'),
							package[2].connection)
				# handle server incoming packages here
				elif package[0] == 'server':
					# auth
					# game state change
					if len(package[1]) == 2:
						if package[1][0] == 'auth':
							clientAuth = False
							print 'Attempting Authentication on: ', package[1][1]
							for client in self.activeClients:
								if client.name == package[1][1]:
									clientAuth = True
									break
							if clientAuth:
								self.sendData(('auth', client.name), package[2].connection)
							else:
								self.sendData(('fail', package[1][1]), package[2].connection)
						elif package[1][0] == 'state':
							package[2].state = package[1][1]
				# handle chat server incoming packages here
				elif package[0] == 'chat':
					print 'Authorized chat server sent package'
					# handle packages from the chat servers
					# like making public/private
					# authing clients
		return task.again