本文整理汇总了Python中pandac.PandaModules.QueuedConnectionReader.dataAvailable方法的典型用法代码示例。如果您正苦于以下问题:Python QueuedConnectionReader.dataAvailable方法的具体用法?Python QueuedConnectionReader.dataAvailable怎么用?Python QueuedConnectionReader.dataAvailable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandac.PandaModules.QueuedConnectionReader
的用法示例。
在下文中一共展示了QueuedConnectionReader.dataAvailable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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
示例2: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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()
示例3: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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
示例4: __init__
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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
示例5: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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
#.........这里部分代码省略.........
示例6: ClientConnection
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
def registerGame(self, game, callback):
''' Tell server we are loaded and ready. The game ID is returned.
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()
示例7: LoginServer
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
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
示例8: __init__
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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
示例9: __init__
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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
示例10: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [as 别名]
class Server(DirectObject):
def __init__(self):
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager,0)
self.activeConnections = [] # Keeps tracks of active connections
#Set up the connection
port_address=9099 #No-other TCP/IP services are using this port
backlog=1000 #If we ignore 1,000 connection attempts, something is wrong!
self.tcpSocket = self.cManager.openTCPServerRendezvous(port_address,backlog)
self.cListener.addConnection(self.tcpSocket)
self.setTaskManagers() #Set the Managers
def tskListenerPolling(self,taskdata):
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
self.broadCast(newConnection) #Broadcasts the Server Message
return Task.cont
def tskReaderPolling(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):
myProcessDataFunction(datagram)
return Task.cont
def setTaskManagers(self):
taskMgr.add(self.tskListenerPolling,"Poll the connection listener",-39)
taskMgr.add(self.tskReaderPolling,"Poll the connection reader",-40)
'''
Terminate all connections.
'''
def terminateAllConnection(self):
for aClient in self.activeConnections:
self.cReader.removeConnections(aClient)
self.activeConnections = []
#Close our listener
self.cManager.closeConnection(self.tcpSocket)
'''
Terminate a connection.
'''
def terminateConnection(self, aClient):
self.cReader.removeConnections(aClient)
'''
PyDatagram for messages
Arguments: message must be a string
'''
def messageData(self, message):
messDat = PyDatagram()
messDat.addUint8(PRINT_MESSAGE)
messDat.addString(message)
return messDat
'''
Broadcast Server Message
'''
def broadCast(self, aClient):
message = self.messageData("Welcome to BaziBaz's Server\nConnection has been estabilished\n")
self.cWriter.send(message, aClient)
示例11: UDPconnection
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
enc_data = self.encode(data)
if len(enc_data) > self.maxlength:
chunks = self.chunks(enc_data, self.maxlength)
nchunks = math.ceil(len(enc_data) / (1.0 * self.maxlength))
identifier = self.multMsgID
self.multMsgID += 1
oakn = [msgtype, identifier, nchunks]
msgtype = MULT
else:
chunks = [enc_data]
nchunks = 1
messages = []
n = 0
for dat in chunks:
msg = {}
msg[SEQN] = seqNum
msg[AKN] = akn
msg[MSG_TYPE] = msgtype
msg[OOL] = out_of_line
if nchunks > 1:
oakn.append(n)
msg[OAKN] = self.encode(oakn)
oakn.pop()
n += 1
else:
msg[OAKN] = self.encode(oakn)
msg[DATA] = dat
msg[ENCODED] = True
msg[ADDR] = None
msg[TIME] = 0
messages.append(msg)
return messages
def _crDatagram(self, msg):
# create Datagram from message
myPyDatagram = PyDatagram()
myPyDatagram.addInt32(msg[SEQN])
myPyDatagram.addInt32(msg[AKN])
myPyDatagram.addInt16(msg[MSG_TYPE])
myPyDatagram.addInt8(msg[OOL])
if not msg[ENCODED]:
myPyDatagram.addString(self.encode(msg[OAKN]))
myPyDatagram.addString(self.encode(msg[DATA]))
else:
myPyDatagram.addString(msg[OAKN])
myPyDatagram.addString(msg[DATA])
return myPyDatagram
def _processData(self, netDatagram):
# convert incoming Datagram to dict
myIterator = PyDatagramIterator(netDatagram)
msg = {}
msg[SEQN] = myIterator.getInt32()
msg[AKN] = myIterator.getInt32()
msg[MSG_TYPE] = myIterator.getInt16()
msg[OOL] = myIterator.getInt8()
msg[OAKN] = self.decode(myIterator.getString())
if not msg[MSG_TYPE] == MULT:
msg[DATA] = self.decode(myIterator.getString())
else:
msg[DATA] = (myIterator.getString())
# msg.append(self.decode(myIterator.getString()))
return msg
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):
# pkg = []
pkg = self._processData(datagram)
tmpaddr = datagram.getAddress()
addr = NetAddress()
addr.setHost(tmpaddr.getIpString(), tmpaddr.getPort())
pkg[ADDR] = addr
data.append(pkg)
return data
def addCommBuffer(self, addr):
cb_id = self.nextID
self.commBuffer.append(commBuffer(id=cb_id, addr=addr, lastRecv=self.time.getFrameTime()))
self.nextID += 1
self.conAddresses = [(cb.addr.getIp(), cb.addr.getPort()) for cb in self.commBuffer]
self.conIDs = [cb.id for cb in self.commBuffer]
return cb_id
def removeCommBuffer(self, cID):
ind = self.getCommBufferByID(cID)
if ind < 0:
raise IndexError
del self.commBuffer[ind]
self.conAddresses = [(cb.addr.getIp(), cb.addr.getPort()) for cb in self.commBuffer]
self.conIDs = [cb.id for cb in self.commBuffer]
def chunks(self, string, n):
return [string[i:i+n] for i in range(0, len(string), n)]
示例12: PSGServer
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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())
#.........这里部分代码省略.........
示例13: Server
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
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')
示例14: Client
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [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)
#.........这里部分代码省略.........
示例15: SocketServer
# 需要导入模块: from pandac.PandaModules import QueuedConnectionReader [as 别名]
# 或者: from pandac.PandaModules.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
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)