本文整理汇总了Python中pandac.PandaModules.QueuedConnectionReader.getData方法的典型用法代码示例。如果您正苦于以下问题:Python QueuedConnectionReader.getData方法的具体用法?Python QueuedConnectionReader.getData怎么用?Python QueuedConnectionReader.getData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandac.PandaModules.QueuedConnectionReader
的用法示例。
在下文中一共展示了QueuedConnectionReader.getData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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)
示例2: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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
示例3: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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()
示例4: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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
示例5: __init__
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [as 别名]
#.........这里部分代码省略.........
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
示例6: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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
#.........这里部分代码省略.........
示例7: ClientConnection
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [as 别名]
#.........这里部分代码省略.........
game (Game): The game to be registered.
callback (function): Funtion that will be called when a response is
received. Callback will be passed one parameter (status).
status = 0 if registration fails
status > 0 the id of the game on success
'''
id = 1
callback(id)
def sendUnitMove(self, movedentity, callback):
''' Send updated entity to server.'''
self.__sendUnitMove(movedentity)
self._respCallback[MSG_UNITMOVE_RES] = callback
def sendUnitAttack(self, fromentity, toentity, callback):
''' Send a message that fromentity attacked toentity. The entities
have been updated from the attack.'''
self.__sendUnitAttack(fromentity, toentity)
self._respCallback[MSG_UNITATTACK_RES] = callback
def sendUnitInfo(self, entity):
''' Send a requst for information about the given entity.'''
self.__sendUnitInfo(entity)
self._respCallback[MSG_UNITINFO_RES] = callback
#--ClientConnection Private Methods----------------------------------------
def __readTask(self, taskdata):
''' 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() # 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 = 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 the server every PING_DELAY seconds to check if it's still
there.'''
LOG.debug('Pinging')
# Add task back into the taskmanager
taskMgr.doMethodLater(PING_DELAY, self.__pingTask, 'serverPingTask', sort=-41)
def __downloadTask(self, Task):
if self.channel.run():
# Still waiting for file to finish downloading.
return task.cont
if not self.channel.isDownloadComplete():
print "Error downloading file."
return task.done
data = self.rf.getData()
print "got data:"
print data
return task.done
示例8: LoginServer
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [as 别名]
#.........这里部分代码省略.........
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
示例9: __init__
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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
示例10: __init__
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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
示例11: SocketServer
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [as 别名]
#.........这里部分代码省略.........
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]
示例12: UDPconnection
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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:
#.........这里部分代码省略.........
示例13: PSGServer
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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())
#.........这里部分代码省略.........
示例14: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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):
#.........这里部分代码省略.........
示例15: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import getData [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)
#.........这里部分代码省略.........