当前位置: 首页>>代码示例>>Python>>正文


Python QueuedConnectionReader.addConnection方法代码示例

本文整理汇总了Python中pandac.PandaModules.QueuedConnectionReader.addConnection方法的典型用法代码示例。如果您正苦于以下问题:Python QueuedConnectionReader.addConnection方法的具体用法?Python QueuedConnectionReader.addConnection怎么用?Python QueuedConnectionReader.addConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pandac.PandaModules.QueuedConnectionReader的用法示例。


在下文中一共展示了QueuedConnectionReader.addConnection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Client

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class Client(DirectObject):
    def __init__(self):
        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager,0)
        self.connection = None #Connection with the server
        
    def connectToServer(self, ip_address="192.168.1.110", port_address=9099):
        #How long to wait until we give up connecting
        timeout = 3000 # 3 seconds
        self.connection = self.cManager.openTCPClientConnection(ip_address,port_address,timeout)
        if self.connection:
            self.cReader.addConnection(self.connection) #Retrieve message from Server
            return True #We connected
        return False #We couldn't succeed
    
    def processMsgData(self, dataGram):
        iterator = PyDatagramIterator(dataGram)
        msgID = iterator.getUint8()
        if msgID == PRINT_MESSAGE:
            msg = iterator.getString()
            print msg
    
    def recieveMessage(self):
        datagram = NetDatagram() #Needed to store the message or data recieved
        if self.cReader.getData(datagram):
            self.processMsgData(datagram)
            
    
    '''
    Closes the connection with the server
    '''
    def disconnectServer(self):
        self.cManager.closeConnection(self.connection)
开发者ID:muadibbm,项目名称:COMP361Project,代码行数:36,代码来源:server_and_client.py

示例2: Client

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class Client():
    
    def __init__(self):
        self.cManager = QueuedConnectionManager()
        self.tcpWriter = ConnectionWriter(self.cManager,0)
        self.tcpReader = QueuedConnectionReader(self.cManager, 0)
        taskMgr.add(self.tskReaderPolling,"Poll the connection reader",-40)
        
        # This fails
        self.conn = self.cManager.openTCPClientConnection(IP_ADDR, PORT, 1000)
        if self.conn:
            print 'Successful connection to', IP_ADDR, ':', PORT
            self.tcpReader.addConnection(self.conn)
            
            self.SendPacket()
            
    def SendPacket(self):
        dg = PyDatagram()
        dg.addUint8(5)
        self.tcpWriter.send(dg, self.conn)
            
    def tskReaderPolling(self, task):
        if self.tcpReader.dataAvailable():
            datagram = NetDatagram()
            if self.tcpReader.getData(datagram):
                print 'client got data'
        return task.cont
开发者ID:czorn,项目名称:Modifire,代码行数:29,代码来源:TestTCP.py

示例3: Client

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class Client(DirectObject): 
    def __init__( self ): 
        print "Initializing client test" 
        
        self.port = 9099
        self.ip_address = "142.157.150.72" 
        self.timeout = 3000             # 3 seconds to timeout 
        
        self.cManager = QueuedConnectionManager() 
        self.cListener = QueuedConnectionListener(self.cManager, 0) 
        self.cReader = QueuedConnectionReader(self.cManager, 0) 
        self.cWriter = ConnectionWriter(self.cManager,0) 
        
        self.Connection = self.cManager.openTCPClientConnection(self.ip_address, self.port, self.timeout) 
        if self.Connection: 
            taskMgr.add(self.tskReaderPolling,"read the connection listener",-40) 
            # this tells the client to listen for datagrams sent by the server 
            
            print "Connected to Server" 
            self.cReader.addConnection(self.Connection) 
            PRINT_MESSAGE = 1 
            myPyDatagram = PyDatagram() 
            myPyDatagram.addUint8(100) 
            # adds an unsigned integer to your datagram 
            myPyDatagram.addString("first string of text") 
            # adds a string to your datagram 
            myPyDatagram.addString("second string of text") 
            # adds a second string to your datagram 
            self.cWriter.send(myPyDatagram, self.Connection) 
            # fires it off to the server 
            
            #self.cManager.closeConnection(self.Connection) 
            #print "Disconnected from Server" 
            # uncomment the above 2 lines if you want the client to 
            # automatically disconnect.  Or you can just 
            # hit CTRL-C twice when it's running to kill it 
            # in windows, I don't know how to kill it in linux 
        else: 
            print "Not connected to Server" 
        
    def tskReaderPolling(self, task): 
        if self.cReader.dataAvailable(): 
            datagram=PyDatagram()  
            if self.cReader.getData(datagram): 
                self.processServerMessage(datagram) 
        return Task.cont        
    
    def processServerMessage(self, netDatagram): 
        myIterator = PyDatagramIterator(netDatagram) 
        print myIterator.getString() 
开发者ID:muadibbm,项目名称:COMP361Project,代码行数:52,代码来源:client_test2.py

示例4: Server

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class Server():
    
    def __init__(self):
        self.cManager = QueuedConnectionManager()
        self.tcpSocket = self.cManager.openTCPServerRendezvous(PORT, 1000)
        self.tcpWriter = ConnectionWriter(self.cManager,0)
        self.tcpListener = QueuedConnectionListener(self.cManager, 0)
        self.tcpListener.addConnection(self.tcpSocket)
        self.tcpReader = QueuedConnectionReader(self.cManager, 0)
        
        taskMgr.add(self.tskListenerPolling,"Poll the connection listener",-39)
        taskMgr.add(self.tskReaderPolling,"Poll the connection reader",-40)
        
    def SendPacket(self):
        dg = PyDatagram()
        dg.addUint8(5)
        self.tcpWriter.send(dg, self.conn)
        
    def tskReaderPolling(self, task):
        if self.tcpReader.dataAvailable():
            datagram = NetDatagram()
            if self.tcpReader.getData(datagram):
                print 'server got data'
                self.SendPacket()
        return task.cont
    
    def tskListenerPolling(self, task):
        if self.tcpListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            netAddress = NetAddress()
            newConnection = PointerToConnection()
        
            if self.tcpListener.getNewConnection(rendezvous, netAddress, newConnection):
                newConnection = newConnection.p()
                self.tcpReader.addConnection(newConnection)
                self.conn = newConnection
                print self.conn.getAddress().getPort()
        return task.cont
开发者ID:czorn,项目名称:Modifire,代码行数:40,代码来源:TestTCP.py

示例5: __init__

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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.

#.........这里部分代码省略.........
开发者ID:H3LLB0Y,项目名称:Warlocks,代码行数:103,代码来源:login_server_core.py

示例6: Server

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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 
#.........这里部分代码省略.........
开发者ID:muadibbm,项目名称:COMP361Project,代码行数:103,代码来源:server_example.py

示例7: ClientConnection

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class ClientConnection(object):
	''' This class creates the communication links to a game server and
		presents an interface for communication.'''
	
	__metaclass__ = Singleton
	
	address        = 'chadrempp.com'
	port           = '9091'
	timeout        = '3000'
	_callback       = None
	_connected      = False
	_authorized   	= False
	_connectedGame 	= None
	_respCallback   = {MSG_AUTH_RES:       None,
					   MSG_MAPLIST_RES:    None,
					   MSG_GAMELIST_RES:   None,
					   MSG_NEWGAME_RES:    None,
					   MSG_JOINGAME_RES:   None}
	def __init__(self):
		''' ClientConnection constructor.'''
		self._cManager   = QueuedConnectionManager()
		self._cListener  = QueuedConnectionListener(self._cManager, 0)
		self._cReader    = QueuedConnectionReader(self._cManager, 0)
		self._cWriter    = ConnectionWriter(self._cManager,0)
	
	def isConnected(self):
		''' Return True if a connection is established, otherwise False.'''
		return self._connected
	
	def isAuthorized(self):
		''' Return True if the connection is authorized, otherwise False.'''
		return self._authorized
	
	def authenticate(self, username, password, callback):
		''' Send authentication request.
			
			username (string): Username for authentication
			password (string): Password for authentication
			callback (function): Funtion that will be called when a response is
				received. Callback will be passed one parameter (status)
					status = 0 if authorization failed
					status = 1 if the user is already authenticated
					status = 2 if an invalid password is supplied
					status = 3 if authentication succeeded
		'''
		self.__sendAuthReq(username, password)
		self._respCallback[MSG_AUTH_RES] = callback
	
	def connect(self, address, port, timeout, callback=None):
		''' Try to connect to the server.
			
			address (String): address for the server
			port (Int): port to connect to
			timeout (Int): how long to wait before giving up (milliseconds)
			callback (function): Funtion that will be called when a response is
				received. Callback will be passed one parameter (status)
					status = True if connection succeeded
					status = False if connection failed
		'''
		if self._connected:
			LOG.notice("Already Connected!")
		else:
			self._connected = False
			try:
				LOG.notice('connecting to %s'%address)
				self._tcpSocket = self._cManager.openTCPClientConnection(address, port, timeout)
				if self._tcpSocket:
					LOG.notice("Opened socket.")
					self._cReader.addConnection(self._tcpSocket)  # receive messages from server
					if self._cReader:
						taskMgr.add(self.__readTask,"Poll the connection reader",-40)
						taskMgr.doMethodLater(PING_DELAY, self.__pingTask, 'serverPingTask', sort=-41)
						self._connected = True
						LOG.notice("Created listener")
					else:
						LOG.error("Couldn't connect to server")
				else:
					LOG.error("Couldn't connect to server")
			except Exception:
				LOG.error("Couldn't connect to server")
		if callback:
			callback(self._connected)
		
	def disconnect(self, callback):
		''' Disconnect from the server.
			
			callback (function): Funtion that will be called when a response is
				received. Callback will be passed one parameter (status)
					status = 1 if connection succeeded
					status = 0 if connection failed
		'''
		if self._connected:
			LOG.notice('Disconnecting...')
			pkg = NetDatagram()
			pkg.addUint16(MSG_DISCONNECT_REQ)
			self._cWriter.send(pkg, self._tcpSocket)
			self._cManager.closeConnection(self._tcpSocket)
			self._connected = False
			if callback != None: callback(1)
		else:
#.........这里部分代码省略.........
开发者ID:crempp,项目名称:psg,代码行数:103,代码来源:ClientConnection.py

示例8: LoginServer

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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.
#.........这里部分代码省略.........
开发者ID:H3LLB0Y,项目名称:Centipede,代码行数:103,代码来源:loginserver.py

示例9: __init__

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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
开发者ID:H3LLB0Y,项目名称:Warlocks,代码行数:73,代码来源:client.py

示例10: __init__

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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
开发者ID:gelatindesign,项目名称:Colony,代码行数:92,代码来源:Server.py

示例11: SocketServer

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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)
#.........这里部分代码省略.........
开发者ID:shubhamgoyal,项目名称:virtual-vision-simulator,代码行数:103,代码来源:socket_server.py

示例12: UDPconnection

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class UDPconnection():
    """
    base class for UDP server and client, handles basic communication (decoding/encoding), buffering and resending
    """
    def __init__(self, port='9099', timeout=3.0, commTicks=50, resendTime=0.33, reliable=0, concurrent=10, maxlength=480):
        self.logger = logging.getLogger('UDPcon')
        self.port = port
        # Start the UDP Connection
        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)
        self.conn = self.cManager.openUDPConnection(self.port)
        self.cReader.addConnection(self.conn)
        self.handlers = {}
        self.nextID = 1
        self.commBuffer = []
        self.conAddresses = []
        self.conIDs = []
        self.timeout = timeout
        self.commTicks = commTicks
        self.commTime = 1.0 / self.commTicks
        self.time = ClockObject()
        self.resendTime = resendTime
        self.reliable = reliable
        self.concurrent = concurrent
        self.maxlength = maxlength
        self.multMsgID = 0
        # receive data
#        taskMgr.add(self.listendata, "Incoming Data Listener", -40)
        self.running = True
        self.threadLock = threading.Lock()
        self.listenThread = threading.Thread(target=self.listendata)
        self.batchThread = threading.Thread(target=self.batch)
        for thread in [self.listenThread, self.batchThread]:
            thread.daemon = True
            thread.start()
        self.handlers[KEEP_ALIVE] = self.reply
        self.handlers[CONFIRM] = self.sync
#        logging.debug('UDPconnection created')
        self.logger.debug('UDPconnection created')

    def batch(self):
        # recurring tasks
        while self.running:
            self.threadLock.acquire()
            self.timenow = self.time.getFrameTime()
            self.sendDataBuffer()
            self.chkCommBuffers()
            self.threadLock.release()
            time.sleep(self.commTime)

    def listendata(self):
        # function that listens for incoming data, updating communication clock and calling handler-functions, should be added to taskMgr
        time.sleep(0.02)
        while self.running:
            time.sleep(0.005)
#            time.sleep(0.1)
            self.time.tick()
            data = self.getData()
            if data:
                self.threadLock.acquire()
                self.timenow = self.time.getFrameTime()
                # we only accept authentication requests from not-connected remote machines, all other incomming data is discarded
                for d in data:
#                    print "incoming: ", d[MSG_TYPE], d[SEQN]
                    if d[MSG_TYPE] == CMSG_AUTH or d[MSG_TYPE] == SMSG_AUTH_RESPONSE:
    #                if d[MSG_TYPE] == CMSG_AUTH:
                        if d[MSG_TYPE] in self.handlers:
                            self.handlers[d[MSG_TYPE]](d[DATA], d[ADDR])
                        continue
                    ind = self.getCommBufferByAddr(d[ADDR])
                    if ind < 0:
                        continue

                    self.commBuffer[ind].lastRecv = self.timenow
                    # remove confirmed messages
                    self.commBuffer[ind].confirm(d[AKN], time=self.timenow)

                    if d[MSG_TYPE] == MULT:
                        if d[SEQN] > 0 and d[SEQN] <= self.commBuffer[ind].rseqNumber:
                            continue    
                        d = self.commBuffer[ind].addPartialMsg(d, time=self.timenow)                    
                    else:
                        if d[OAKN]:
                            self.commBuffer[ind].remove(d[OAKN])

                    # discard message if already received
                    if d[SEQN] > 0 and d[SEQN] <= self.commBuffer[ind].rseqNumber:
                        continue

                    execute = []
                    # unreliable messages are always executed when they are received without sending a confirmation
                    if d[SEQN] < 0:
                        execute = [d]
                    else:
                        # if received message is the next in line or can be executed out of line -> execute=1, otherwise store in recvBuffer
                        if d[SEQN] == self.commBuffer[ind].rseqNumber + 1:
                            self.commBuffer[ind].rseqNumber += 1
                            execute = [d]
                        else:
#.........这里部分代码省略.........
开发者ID:lgo33,项目名称:NetPanda,代码行数:103,代码来源:UDPconnection_thread.py

示例13: PSGServer

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class PSGServer(object):
	''' The main server that listens for connections and manages active games.
		This also runs the console which can interact with the server.'''
		
	# registeredUsers is a list of User objects of registered users
	registeredUsers = []
	# connectedUsers is a list of User objects of currently connected users
	connectedUsers  = []
	# connections is a list of Connection objects
	connections =[]
	# Connections that have not responded to their keepalive request.
	# A dictionary of the form (Connection, pingtime)
	pingNonResponders = {}
	# games is a list of active GameStateServer objects
	games = []

	def __init__(self):
		''' Initialize the server.'''
		
		import __builtin__
		__builtin__.LOG = LogConsole()
		
		print('Starting PSG Server ...')
		self._cManager  = QueuedConnectionManager()
		self._cListener = QueuedConnectionListener(self._cManager, 0)
		self._cReader   = QueuedConnectionReader(self._cManager, 0)
		self._cWriter   = ConnectionWriter(self._cManager,0)
		
		#TODO - Load user file (DB)
		self.registeredUsers =[ServerPlayer('chad','password1'),
							   ServerPlayer('josh','password2'),
							   ServerPlayer('james','password3')]
		
		# Map store
		self._mapStore = MapStore()
		
		# Open socket
		self._tcpSocket = self._cManager.openTCPServerRendezvous(PORT,BACKLOG)
		self._cListener.addConnection(self._tcpSocket)
		
		# Setup interfaces
		self._console = InterfaceConsole(self)
		
		# Setup system tasks
		taskMgr.add(self.__listenTask, 'serverListenTask', -40)
		taskMgr.add(self.__readTask, 'serverReadTask', -39)
		taskMgr.doMethodLater(PING_DELAY, self.__pingTask, 'serverPingTask', sort=-41)
		taskMgr.doMethodLater(1, self.__checkPingRespTask, 'serverCheckPingRespTask', sort=-10)
		
		print('Server initialized')
	
	
	def __listenTask(self, Task):
		''' This task listens for connections. When a connection is made it
			adds the connection to the clients list and begins listening to
			that connection.'''
		if self._cListener.newConnectionAvailable():
			rendezvous = PointerToConnection()
			netAddress = NetAddress()
			newConnection = PointerToConnection()
			
			if self._cListener.getNewConnection(rendezvous,netAddress,newConnection):
				newConnection = newConnection.p()
				if newConnection not in self.connections:
					self.connections.append(newConnection)
					self._cReader.addConnection(newConnection)     # Begin reading connection
					self._console.printNotice('Connection from %s'%netAddress.getIpString())
				else:
					self._console.printNotice('%s: already connected'%(newConnection.getAddress().getIpString()))
		return Task.cont
	
	def __readTask(self, Task):
		''' This task listens for any messages coming in over any connections.
			If we get a connection passes it to the datagram handler.'''
		if self._cReader.dataAvailable():
			datagram=NetDatagram()
			if self._cReader.getData(datagram):
				data = PyDatagramIterator(datagram)
				msgID = data.getUint16()
			else:
				data = None
				msgID = MSG_NONE
		else:
			datagram = None
			data = None
			msgID = MSG_NONE
		if msgID is not MSG_NONE:
			self.__handleDatagram(data, msgID, datagram.getConnection())
		return Task.cont
	
	def __pingTask(self, Task):
		''' Ping all clients every PING_DELAY seconds to check for those who
			have dropped their connection.'''
		
		notice = 'Pinging: '
		
		for c in self.connections:
			# Don't ping connections we're still waiting on
			if c not in self.pingNonResponders.keys():
				notice = '%s%s '%(notice, c.getAddress().getIpString())
#.........这里部分代码省略.........
开发者ID:crempp,项目名称:psg,代码行数:103,代码来源:GameServer.py

示例14: Server

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
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):
#.........这里部分代码省略.........
开发者ID:H3LLB0Y,项目名称:Centipede,代码行数:103,代码来源:server.py

示例15: Client

# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import addConnection [as 别名]
class Client(DirectObject):
    
    #-----------------
    # Initialization
    #-----------------

    def __init__(self):
        self.log = Log()
        self.log.Open('client.txt')

        self.clientSnapshotHandler = ClientSnapshotHandler()
        
        self.accept(EngineLoadedEvent.EventName, self.OnEngineLoadedEvent)

        self.fsm = ClientFSM(self)
        self.fsm.request('CreateNetworkObjects')
        
        self.lastServerPacketTimestamp = 0
        

    def CreateNetworkObjects(self):
        if(self.CreateUDPConnection() and self.CreateTCPConnection()):
            self.dataHandler = ClientDataHandler(self)
            self.reliablePacketController = ReliablePacketController(self.cWriter, self.conn, self.dataHandler)
            self.unreliablePacketController = UnreliablePacketController(self.cWriter, self.conn, self.dataHandler)
            self.tcpPacketController = TCPPacketController(self.tcpWriter, self.tcpReader, self.cManager, self.dataHandler)
            self.dataHandler.SetPacketControllers(self.reliablePacketController, self.unreliablePacketController, self.tcpPacketController)
                
            self.ListenForIncomingTraffic()
            return True

        return False
    
    def CreateUDPConnection(self):
        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager,0)
        self.conn = self.cManager.openUDPConnection(Globals.PORT_CLIENT_LISTENER)

        if(self.conn):
            self.log.WriteLine('Connection on %s okay.' % (Globals.PORT_CLIENT_LISTENER))
        else:
            self.log.WriteError('Connection on %s failed.' % (Globals.PORT_CLIENT_LISTENER))
            Globals.PORT_CLIENT_LISTENER += 1
            self.log.WriteError('Retrying on %s .' % (Globals.PORT_CLIENT_LISTENER))
            self.conn = self.cManager.openUDPConnection(Globals.PORT_CLIENT_LISTENER)
            if(self.conn):
                self.log.WriteLine('Connection on %s okay.' % (Globals.PORT_CLIENT_LISTENER))
            else:
                self.log.WriteError('Connection on %s failed.' % (Globals.PORT_CLIENT_LISTENER))
                self.log.WriteError('Connection unsuccessful, exiting Client')
                return False

        self.cReader.addConnection(self.conn)

        return True
    
    def CreateTCPConnection(self):
        self.tcpWriter = ConnectionWriter(self.cManager,0)
        self.tcpReader = QueuedConnectionReader(self.cManager, 0)
        return True
    
    #---------------------
    # Listening for data
    #---------------------

    def ListenForIncomingTraffic(self):
        taskMgr.add(self.UDPPacketListenTask, "UDPPacketListenTask")
        taskMgr.add(self.TCPPacketListenTask, "TCPPacketListenTask", -40)

    def UDPPacketListenTask(self, task):
        while self.cReader.dataAvailable():
            datagram = NetDatagram()
            if self.cReader.getData(datagram):
                #print 'PACKET', datagram
                data = PyDatagramIterator(datagram)
                ip = datagram.getAddress().getIpString()
                port = datagram.getAddress().getPort()
                peerAddr = NetAddress()
                peerAddr.setHost(ip, port)
                
                packetType = data.getUint8()
                if(packetType == Packet.PC_RELIABLE_PACKET):
                    self.reliablePacketController.OnPacketReceived(data, peerAddr)
                elif(packetType == Packet.PC_UNRELIABLE_PACKET):
                    self.unreliablePacketController.OnPacketReceived(data, peerAddr)
                elif(packetType == Packet.PC_ENVIRONMENT_PACKET):
                    self.dataHandler.OnDataReceived(data, peerAddr, Packet.PC_ENVIRONMENT_PACKET)

        return Task.cont
    
    def TCPPacketListenTask(self, task):
        if self.tcpReader.dataAvailable():
            datagram = NetDatagram()
            if self.tcpReader.getData(datagram):
                data = PyDatagramIterator(datagram)
                ip = datagram.getAddress().getIpString()
                port = datagram.getAddress().getPort()
                peerAddr = NetAddress()
                peerAddr.setHost(ip, port)
#.........这里部分代码省略.........
开发者ID:czorn,项目名称:Modifire,代码行数:103,代码来源:Client.py


注:本文中的pandac.PandaModules.QueuedConnectionReader.addConnection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。