本文整理汇总了Python中panda3d.core.QueuedConnectionReader.dataAvailable方法的典型用法代码示例。如果您正苦于以下问题:Python QueuedConnectionReader.dataAvailable方法的具体用法?Python QueuedConnectionReader.dataAvailable怎么用?Python QueuedConnectionReader.dataAvailable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.core.QueuedConnectionReader
的用法示例。
在下文中一共展示了QueuedConnectionReader.dataAvailable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TCP
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class TCP():
def __init__(self, _core):
print ("TCP Protocol Startup...")
self.core = _core
self.config = self.core.client.config
# Connection on TCP
self.tcpConnection = None
def start(self):
self.setupTCP()
self.startTCPTasks()
def setupTCP(self):
self.tcpManager = QueuedConnectionManager()
self.tcpReader = QueuedConnectionReader(self.tcpManager, 0)
self.tcpWriter = ConnectionWriter(self.tcpManager, 0)
def startTCPTasks(self):
taskMgr.add(self.tcpReaderTask, "tcpReaderTask", -10)
print ("TCP Reader Started")
def tcpReaderTask(self, task):
"""
Handle any data from clients by sending it to the Handlers.
"""
while 1:
(datagram, data, opcode) = self.tcpNonBlockingRead(self.tcpReader)
if opcode is MSG_NONE:
# Do nothing or use it as some 'keep_alive' thing.
break
else:
# Handle it
self.core.packetManager.handlePacket(opcode, data)
return Task.cont
# TCP NonBlockingRead??
def tcpNonBlockingRead(self, qcr):
"""
Return a datagram collection and type if data is available on
the queued connection udpReader
"""
if self.tcpReader.dataAvailable():
datagram = NetDatagram()
if self.tcpReader.getData(datagram):
data = DatagramIterator(datagram)
opcode = data.getUint8()
else:
data = None
opcode = MSG_NONE
else:
datagram = None
data = None
opcode = MSG_NONE
# Return the datagram to keep a handle on the data
return (datagram, data, opcode)
def connectToServer(self, _ip, _port):
self.tcpConnection = self.tcpManager.openTCPClientConnection(_ip, _port, 1000)
if self.tcpConnection != None:
self.tcpReader.addConnection(self.tcpConnection)
# Close the main menu and move the client into the game
# for now we will make a shortcut
#self.clientManager.guiManager.menu.hide()
示例2: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
except:
pass
self.loginHandler()
#send packet
myPyDatagram = PyDatagram()
myPyDatagram.addUint8(1)
myPyDatagram.addString(self.username)
myPyDatagram.addString('_')
myPyDatagram.addString(self.password)
self.cWriter.send(myPyDatagram,self.connection)
#receive packet
datagram = NetDatagram()
if self.cReader.getData(datagram):
myProcessDataFunction(datagram)
return False
def loginHandler(self):
self.username = raw_input("Enter username: ")
self.password = raw_input("Enter password: ")
def myProcessDataFunction(netDatagram):
myIterator = PyDatagramIterator(netDatagram)
msgID = myIterator.getUnit8()
if msgID == 1:
msgToPrint = myIterator.getString()
print msgToPrint
def closeConnection(self):
if self.connection != None:
taskMgr.remove('updateRoutine-Main')
taskMgr.remove('updateRoutine-Connection')
taskMgr.remove('checkConnection')
self.cManager.closeConnection(self.connection)
self.connection = None
def sendRequest(self, requestCode, args = {}):
if self.connection != None:
request = ServerRequestTable.get(requestCode)
if request != None:
request.set(self.cWriter, self.connection)
request.send(args)
def handleResponse(self, responseCode, data):
#Prepare a response packet to be processed.
#If the following response code exists, create an instance of this
#specific response using its data to be executed.
response = ServerResponseTable.get(responseCode)
if response != None:
response.set(main)
response.execute(data)
def checkConnection(self, task):
if not self.cReader.isConnectionOk(self.connection):
self.closeConnection()
self.showDisconnected(0)
return task.done
return task.again
def showDisconnected(self, status):
if status == 0:
result = DatabaseHelper.dbSelectRowByID('msg', 'msg_id', 43)
main.createMessageBox(0, result['msg_text'], main.switchEnvironment, ['Login'])
elif status == 1:
result = DatabaseHelper.dbSelectRowByID('msg', 'msg_id', 44)
main.createMessageBox(0, result['msg_text'], main.switchEnvironment, ['Login'])
def updateRoutine(self, task):
#A once-per-frame task used to read packets from the socket.
while self.cReader.dataAvailable():
# Create a datagram to store all necessary data.
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
# Prepare the datagram to be iterated.
data = PyDatagramIterator(datagram)
# Retrieve a "short" that contains the response code.
responseCode = data.getUint16()
# Pass into another method to execute the response.
if responseCode != 0:
self.handleResponse(responseCode, data)
return task.cont
示例3: World
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
def disconnect(self):
pkg = PyDatagram()
pkg.addUint16(119)
self.cWriter.send(pkg,self.connection)
sys.exit()
def requestStop(self):
pkg = PyDatagram()
pkg.addUint16(115)
self.cWriter.send(pkg,self.connection)
def stopPlayer(self, data):
id = data.getInt32()
if id != self.id:
self.opponents[id].character.stop()
self.opponents[id].character.pose("walk",5)
def movePlayer(self, data):
id = data.getInt32()
x = data.getFloat32()
y = data.getFloat32()
z = data.getFloat32()
rotation = data.getFloat32()
if id == self.id:
self.ralph.setPos(x, y, z)
self.ralph.setH(rotation)
else:
self.opponents[id].character.setPos(x,y,z)
self.opponents[id].character.setH(rotation)
self.opponents[id].character.loop("run", restart = 0)
self.miniMap.updateTeamMatePos(id, x, y)
def check(self):
while self.cReader.dataAvailable():
print "data here"
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
data = PyDatagramIterator(datagram)
responseCode = data.getUint16()
print responseCode
if responseCode == 201:
self.getPlayer(data)
elif responseCode == 202:
self.register(data)
elif responseCode == 203:
self.getOpponent(data)
elif responseCode == 214:
self.movePlayer(data)
elif responseCode == 215:
self.stopPlayer(data)
elif responseCode == 219:
self.dropPlayer(data)
else:
print "nothing found"
def heartbeat(self, task):
pkg = PyDatagram()
pkg.addUint16(113)
self.cWriter.send(pkg,self.connection)
return task.again
def updateRoutine(self,task):
self.check()
return task.again;
def login(self, task):
示例4: World
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
self.sendRequest(msg)
def composeStringMessage(self, msg):
myPyDatagram = PyDatagram()
myPyDatagram.addString(msg)
return myPyDatagram
def retrieveStringMessage(self,datagram):
myIterator = PyDatagramIterator(datagram)
msg = myIterator.getString()
#print msg, " received"
return msg
# def sendRequest(self):
# if(self.received):
# print "->Client request:"
# # Send a request to the server
# mylist = ["apple", "ball", "cat", "dog"]
#
# msg = random.choice(mylist)
# request = self.composeStringMessage(msg)
# ack = self.cWriter.send(request,self.connection)
# print msg, " sent"
# self.received = 0
def sendRequest(self, msg):
request = self.composeStringMessage(msg)
ack = self.cWriter.send(request,self.connection)
#print msg, " sent"
#self.received = 0
def receiveResponse(self):
#print "<-Server response:"
while self.cReader.dataAvailable():
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
msg = self.retrieveStringMessage(datagram)
msgs = msg.split(' ')
#print msgs[0]
if msgs[0] == REGISTER_SUCCESSFUL:
self.registerSuccessfulResponse()
elif msgs[0] == USERNAME_EXIST:
self.usernameExistResponse()
elif msgs[0] == LOGIN_SUCCESSFUL:
self.loginSuccessfulResponse(msgs[1])
elif msgs[0] == ADD_NEW_PLAYER:
self.addNewPlayerResponse(msgs[1])
elif msgs[0] == LOGIN_FAIL:
self.loginFailResponse()
elif msgs[0] == LOGOUT:
self.logoutResponse(msgs[1])
elif msgs[0] == UPDATE_PLAYER_MOVE_RESPONSE:
self.updateMoveResponse(msgs[1])
elif msgs[0] == PANDA_ATTACK:
self.pandaAttackResponse(msgs[1])
#self.received = 1
# def communicate(self):
# #print "communicate"
# #self.sendRequest()
# self.receiveResponse()
def updateRoutine(self,task):
#self.communicate()
示例5: login
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
self.password.reparentTo(self.frame)
self.userTextbox = DirectEntry(text = "" ,scale=.05,pos=(.1,0,0), command=self.setUserText,initialText="username", numLines = 1,focus=1,focusInCommand=self.clearUserText, focusOutCommand=self.getUserText)
self.passTextbox = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.2),command=self.setPassText,initialText="password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
self.userTextbox.reparentTo(self.frame)
self.passTextbox.reparentTo(self.frame)
self.submitBtn = DirectButton(text = ("Submit", "Login", "Submit", "disabled"), scale=.08, command=self.func1, pos=(0.8, 0.0, -0.90))
self.registerBtn = DirectButton(text = ("Register", "Register", "Register", "disabled"), scale=.075, command=self.clickedRegister, pos=(0.5, 0.0, -0.90))
self.cancelBtn = DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedCancel, pos=(0.2, 0.0, -0.90))
self.submitBtn.reparentTo(self.frame)
self.cancelBtn.reparentTo(self.frame)
self.registerBtn.reparentTo(self.frame)
def createRegisterWindow(self):
self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
frameSize=(-1, 1, -1, 1),#(Left,Right,Bottom,Top)
pos=(-0.5, 0, 0.5))
self.username = OnscreenText(text = "Username:", pos = (-0.1, 0.0), scale = 0.05,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
self.password = OnscreenText(text="Password: ", pos = (-0.1, -0.2), scale=0.05, fg=(1, 0.5,0.5,1), align=TextNode.ACenter, mayChange=0)
self.cpassword = OnscreenText(text="Confirm Password: ", pos = (-0.15, -0.4), scale=0.05, fg=(1, 0.5,0.5,1), align=TextNode.ACenter, mayChange=0)
self.username.reparentTo(self.frame)
self.password.reparentTo(self.frame)
self.cpassword.reparentTo(self.frame)
self.regInputUser = DirectEntry(text = "" ,scale=.05,pos=(.1,0,0), command=self.setUserText,initialText="username", numLines = 1,focus=1,focusInCommand=self.clearUserText, focusOutCommand=self.getUserText)
self.regInputPass = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.2),command=self.setPassText,initialText="password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
self.regInputCPass = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.4),command=self.setPassText,initialText="confirm password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
self.regInputUser.reparentTo(self.frame)
self.regInputPass.reparentTo(self.frame)
self.regInputCPass.reparentTo(self.frame)
self.registerBtn = DirectButton(text = ("Register", "Register", "Register", "disabled"), scale=.075, command=self.clickedRegRegister, pos=(0.8, 0.0, -0.90))
self.cancelBtn = DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedRegCancel, pos=(0.2, 0.0, -0.90))
self.cancelBtn.reparentTo(self.frame)
self.registerBtn.reparentTo(self.frame)
def check(self):
while self.cReader.dataAvailable():
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
data = PyDatagramIterator(datagram)
responseCode = data.getUint16()
if responseCode == 1:
self.getInt(data)
elif responseCode == 201: #login code
if (self.getString(data)=="Unsuccessful login"): #appears if login unsuccessful
print " "
print "Unsuccessful login"
print " "
self.createLoginWindow()
else:
print "Your are logged in" #appear if login successful
self.createLoginWindow()#appears the login options
self.showRalph()
elif responseCode == 203: #register code
if (self.getString(data)=="Registration successful"): #appear if registration was successful
print "You are now registered"
print "Please login" #user must login
print " "
self.createLoginWindow()
else:
print " "#appear if registration wasn't successful
print "Registration was unsuccessful. Pick a different username and please try again "
print " "
self.createLoginWindow()#user must attempt to register again
elif responseCode == 4:
示例6: Connection
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class Connection(GlobalClockMixin, TaskMixin):
def __init__(self, base, host, port):
self.base = base
self.host = host
self.port = port
self._conn = None
self._retry_elapsed = 0
self._retry_next = 0
self._data_last_received = 0
self.manager = QueuedConnectionManager()
self.reader = QueuedConnectionReader(
self.manager,
0, # number of threads
)
# we're using our own protocol so we don't want panda reading our headers and getting
# all foobared by it (not setting raw mode causes `dataAvailable` to block
# once there is actually data to process)
self.reader.setRawMode(True)
self.writer = ConnectionWriter(
self.manager,
0, # number of threads
)
def connect(self, connected_callback, task):
"""
Attempts to connect to the server and if unable to will retry adding
a second to the wait time to each consecutive failure.
"""
self._retry_elapsed += self.get_dt()
if self._retry_elapsed < self._retry_next:
return task.cont
logging.debug(
'attempting to connect to server at %s:%d',
self.host,
self.port
)
self._conn = self.manager.openTCPClientConnection(
self.host,
self.port,
10000, # timeout ms
)
if self._conn:
logging.debug('connection established')
self.reader.addConnection(self._conn)
# reset the counters in case the connection drops and we have to restart the
# connection process
self._retry_elapsed = 0
self._retry_next = 0
# add a task to poll the connection for data
self.add_task(
self.task_read_polling,
name='connection_reader_poll',
sort=-39,
)
connected_callback()
return
# no connection so retry in a bit
self._retry_elapsed = 0
if self._retry_next == 0:
self._retry_next = 1
elif self._retry_next > 9:
self._retry_next = 10
else:
self._retry_next += 1
logging.error(
'Unable to connect to server %s:%s, will retry in %d seconds',
self.host,
self.port,
self._retry_next,
)
return task.cont
def task_read_polling(self, task):
if self.reader.dataAvailable():
logging.debug('data available from server')
datagram = Datagram()
if self.reader.getData(datagram):
logging.debug('received data from server: %s', datagram)
logging.debug('received data from server: %s', datagram.getMessage())
# TODO: provide a way to supply a data callback
self._data_last_received = 0
else:
# no data received
logging.debug('no data')
self._data_last_received += self.get_dt()
#.........这里部分代码省略.........
示例7: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class Server:
def __init__(self):
self.activeConnections = [] # lists all connections
self.players = {} # keys are the players logins, values are the players datagram connections
self.parties = {} # keys are the parties names, values are dicts representing parties data
self.sessions = {} # keys are the datagram connections, values are dicts storing the characters of the player and its party
self.playersinlobby = [] # lists players in the party screen
self.charid = 0 # used for random team generation
self.chars = [] # lists of dicts representing characters data
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cReader.setTcpHeaderSize(4)
self.send = Send(self.cManager)
port = 3001
if len(sys.argv) > 1:
port = sys.argv[1]
self.tcpSocket = self.cManager.openTCPServerRendezvous(port, 10)
self.cListener.addConnection(self.tcpSocket)
print("Server listening on port", port)
taskMgr.add(self.tskListenerPolling, "Poll the connection listener", -39)
taskMgr.add(self.tskReaderPolling, "Poll the connection reader", -40)
def processData(self, datagram):
iterator = PyDatagramIterator(datagram)
source = datagram.getConnection()
callback = iterator.getString()
getattr(globals()[callback], 'execute')(self, iterator, source)
def updateAllPartyLists(self):
parties = deepcopy(self.parties)
for party in list(parties.values()):
del party['map']['tiles']
for player in self.playersinlobby:
self.send.UPDATE_PARTY_LIST(parties, player)
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)
self.cReader.addConnection(newConnection)
print('A new client is connected', newConnection)
return Task.cont
def tskReaderPolling(self, taskdata):
if self.cReader.dataAvailable():
datagram=NetDatagram()
if self.cReader.getData(datagram):
self.processData(datagram)
return Task.cont
示例8: TCP
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class TCP():
def __init__(self, _core):
print ("TCP Protocol Startup...")
self.core = _core
self.config = self.core.server.config
def start(self):
self.setupTCP()
self.startTCPTasks()
def setupTCP(self):
self.tcpManager = QueuedConnectionManager()
self.tcpReader = QueuedConnectionReader(self.tcpManager, 0)
self.tcpWriter = ConnectionWriter(self.tcpManager, 0)
self.tcpListener = QueuedConnectionListener(self.tcpManager, 0)
self.tcpSocket = self.tcpManager.openTCPServerRendezvous(self.config.TCPPORT, self.config.BACKLOG)
self.tcpListener.addConnection(self.tcpSocket)
print ("Started Server on: ", self.config.HOSTNAME, self.config.TCPPORT)
def startTCPTasks(self):
taskMgr.add(self.tcpListenerTask, "tcpListenerTask", 0)
print ("TCP Listener Started")
taskMgr.add(self.tcpReaderTask, "tcpReaderTask", -10)
print ("TCP Reader Started")
taskMgr.add(self.tcpDisconnectionHandler, "tcpDisconnectionHandler", 20)
print ("TCP Disconnection Handler Started")
# TCP Listener Task
def tcpListenerTask(self, task):
"""
Accept new incoming connection from clients, related to TCP
"""
# Handle new connection
if self.tcpListener.newConnectionAvailable():
rendezvous = PointerToConnection()
netAddress = NetAddress()
newConnection = PointerToConnection()
if self.tcpListener.getNewConnection(rendezvous, netAddress, newConnection):
newConnection = newConnection.p()
# Tell the reader about the new TCP connection
self.tcpReader.addConnection(newConnection)
# Handle the connection depending on persistent or not
if self.core.server.isPersistent:
self.core.handleConnection(generateUUID(), newConnection, netAddress)
else:
self.core.createPlayerObject(generateUUID(),newConnection, netAddress)
print ("Server: New Connection from -", str(netAddress.getIpString()))
else:
print ("Server: Connection Failed from -", str(netAddress.getIpString()))
return Task.cont
def tcpReaderTask(self, task):
"""
Handle any data from clients by sending it to the Handlers.
"""
while 1:
(datagram, data, opcode) = self.tcpNonBlockingRead(self.tcpReader)
if opcode is MSG_NONE:
# Do nothing or use it as some 'keep_alive' thing.
break
else:
# Handle it
self.core.packetManager.handlePacket(opcode, data, datagram.getAddress())
return Task.cont
# TCP NonBlockingRead??
def tcpNonBlockingRead(self, qcr):
"""
Return a datagram collection and type if data is available on
the queued connection udpReader
"""
if self.tcpReader.dataAvailable():
datagram = NetDatagram()
if self.tcpReader.getData(datagram):
data = DatagramIterator(datagram)
opcode = data.getUint8()
else:
data = None
opcode = MSG_NONE
else:
datagram = None
data = None
opcode = MSG_NONE
#.........这里部分代码省略.........
示例9: MyApp
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
host = "localhost"
port = 9252
self.connection = self.cManager.openTCPClientConnection(host, port, 10000)
self.received = 1
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine')
taskMgr.add(self.message, 'message')
def message(self, task):
self.option = 0
self.option = str(raw_input("1-Send integer\n2-Send string\n3-Send short\n4-Send float\n"))
if self.option == "1":
msg = int(100 * random.random()) - 50
request = self.intRequest(msg)
self.cWriter.send(request,self.connection)
print "sent ", msg
taskMgr.remove('message')
elif self.option == "2":
msg = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for x in range(7))
request = self.stringRequest(msg)
self.cWriter.send(request,self.connection)
print "sent ", msg
taskMgr.remove('message')
elif self.option == "3":
msg = int(100 * random.random())
request = self.shortRequest(msg)
self.cWriter.send(request,self.connection)
print "sent ", msg
taskMgr.remove('message')
elif self.option == "4":
msg = 100 * random.random()
request = self.floatRequest(msg)
self.cWriter.send(request,self.connection)
print "sent ", msg
taskMgr.remove('message')
def intRequest(self, msg):
pkg = PyDatagram()
pkg.addUint16(1)
pkg.addInt32(msg)
return pkg
def stringRequest(self, msg):
pkg = PyDatagram()
pkg.addUint16(2)
pkg.addString(msg)
return pkg
def shortRequest(self, msg):
pkg = PyDatagram()
pkg.addUint16(3)
pkg.addUint16(msg)
return pkg
def floatRequest(self, msg):
pkg = PyDatagram()
pkg.addUint16(4)
pkg.addFloat32(msg)
return pkg
def registerRequest(self, username, password):
pkg = PyDatagram()
pkg.addUint16(102)
pkg.addString(username)
pkg.addString(password)
return pkg
def check(self):
while self.cReader.dataAvailable():
print "data here"
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
data = PyDatagramIterator(datagram)
responseCode = data.getUint16()
print responseCode
if responseCode == 1:
self.getInt(data)
elif responseCode == 2:
self.getString(data)
elif responseCode == 3:
self.getShort(data)
elif responseCode == 4:
self.getFloat(data)
else:
print "nothing found"
def getInt(self, data):
#.........这里部分代码省略.........
示例10: OldNetworkSystem
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class OldNetworkSystem(sandbox.EntitySystem):
def init(self, port=2000, server="127.0.0.1", serverPort=1999, backlog=1000, compress=False):
self.packetCount = 0
self.port = port
self.serverPort = serverPort
self.serverIP = server
self.serverAddress = NetAddress()
self.serverAddress.setHost(server, serverPort)
self.cManager = QueuedConnectionManager()
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
self.udpSocket = self.cManager.openUDPConnection(self.port)
self.cReader.addConnection(self.udpSocket)
def begin(self):
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):
myIterator = PyDatagramIterator(datagram)
msgID = myIterator.getUint8()
#If not in our protocol range then we just reject
if msgID < 0 or msgID > 200:
return
#Order of these will need to be optimized later
#We now pull out the rest of our headers
remotePacketCount = myIterator.getUint8()
ack = myIterator.getUint8()
acks = myIterator.getUint16()
hashID = myIterator.getUint16()
sourceOfMessage = datagram.getConnection()
if msgID == protocol.NEW_SHIP:
log.info("New ship")
playerPilotID = myIterator.getUint16()
shipID = myIterator.getUint16()
shipName = myIterator.getString()
health = myIterator.getUint8()
position = Point3(myIterator.getFloat32(), myIterator.getFloat32(), myIterator.getFloat32())
linearVelocity = Vec3(myIterator.getFloat32(), myIterator.getFloat32(), myIterator.getFloat32())
rotiation = VBase3(myIterator.getFloat32(), myIterator.getFloat32(), myIterator.getFloat32())
angularVelocity = Vec3(myIterator.getFloat32(), myIterator.getFloat32(), myIterator.getFloat32())
ship = sandbox.addEntity(shipID)
component = ships.PilotComponent()
component.accountEntityID = playerPilotID
ship.addComponent(component)
component = ships.BulletPhysicsComponent()
messenger.send("addSpaceShip", [component, shipName, position, linearVelocity])
ship.addComponent(component)
component = ships.ThrustComponent()
ship.addComponent(component)
component = ships.InfoComponent()
component.health = health
component.name = shipName
ship.addComponent(component)
elif msgID == protocol.PLAYER_MOVED_SHIP:
log.debug("Player moved ship")
accountID = myIterator.getUint16()
shipID = myIterator.getUint16()
print sandbox.components[shipID]
universals.shipNode = sandbox.components[shipID][ships.BulletPhysicsComponent].nodePath
elif msgID == protocol.LOGIN_ACCEPTED:
log.info("Login accepted")
entityID = myIterator.getUint8()
universals.day = myIterator.getFloat32()
elif msgID == protocol.LOGIN_DENIED:
log.info("Login failed")
def genBasicData(self, proto):
myPyDatagram = PyDatagram()
myPyDatagram.addUint8(proto)
myPyDatagram.addUint8(self.packetCount)
myPyDatagram.addUint8(0)
myPyDatagram.addUint16(0)
myPyDatagram.addUint16(0)
self.packetCount += 1
return myPyDatagram
def sendLogin(self, username, hashpassword):
datagram = self.genBasicData(protocol.LOGIN)
datagram.addString(username)
datagram.addString(hashpassword)
universals.log.debug("sending login")
self.sendData(datagram)
def sendData(self, datagram):
sent = self.cWriter.send(datagram, self.udpSocket, self.serverAddress)
while not sent:
print "resending"
sent = self.cWriter.send(datagram, self.udpSocket, self.serverAddress)
示例11: SocketTCP
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class SocketTCP(ShowBase):
def __init__(self, _parent=None):
ShowBase.__init__(self, windowType = 'none')
print ("TCP Protocol Startup...")
#self.parent = _parent
#self.config = self.parent.server.config
# tmp config
self.tcpport = 6000
self.backlog = 10
self.hostname = '127.0.0.1'
self.sendPacketQueue = None
def startAll(self):
self.setupTCP()
self.startTCPTasks()
def setupTCP(self):
self.tcpManager = QueuedConnectionManager()
self.tcpReader = QueuedConnectionReader(self.tcpManager, 0)
self.tcpWriter = ConnectionWriter(self.tcpManager, 0)
self.tcpListener = QueuedConnectionListener(self.tcpManager, 0)
self.tcpSocket = self.tcpManager.openTCPServerRendezvous(self.tcpport, self.backlog)
self.tcpListener.addConnection(self.tcpSocket)
print ("Started Server on: ", self.hostname, self.tcpport)
def startTCPTasks(self):
taskMgr.add(self.tcpListenerTask, "tcpListenerTask", 0)
print ("TCP Listener Started")
taskMgr.add(self.tcpReaderTask, "tcpReaderTask", -10)
print ("TCP Reader Started")
taskMgr.add(self.tcpDisconnectionHandler, "tcpDisconnectionHandler", 20)
print ("TCP Disconnection Handler Started")
taskMgr.add(self.tcpQueuedSendHandlerTask, "tcpQueuedSendhandlerTask", -11)
print ("TCP Queued Send Handler Started")
# TCP Listener Task
def tcpListenerTask(self, task):
"""
Accept new incoming connection from clients, related to TCP
"""
# Handle new connection
if self.tcpListener.newConnectionAvailable():
rendezvous = PointerToConnection()
netAddress = NetAddress()
newConnection = PointerToConnection()
if self.tcpListener.getNewConnection(rendezvous, netAddress, newConnection):
newConnection = newConnection.p()
# Tell the reader about the new TCP connection
self.tcpReader.addConnection(newConnection)
#self.core.createPlayerObject(generateUUID(),newConnection, netAddress)
print ("Server: " + str(generateUUID), str(netAddress.getIpString()))
else:
print ("Server: Connection Failed from -", str(netAddress.getIpString()))
return Task.cont
def tcpReaderTask(self, task):
"""
Handle any data from clients by sending it to the Handlers.
"""
while 1:
(datagram, data, opcode) = self.tcpNonBlockingRead(self.tcpReader)
if opcode is MSG_NONE:
# Do nothing or use it as some 'keep_alive' thing.
break
else:
# Handle it
#self.core.packetManager.handlePacket(opcode, data, datagram.getAddress())
print("Set Packet Handler to handle packets!")
return Task.cont
# TCP NonBlockingRead??
def tcpNonBlockingRead(self, qcr):
"""
Return a datagram collection and type if data is available on
the queued connection udpReader
"""
if self.tcpReader.dataAvailable():
datagram = NetDatagram()
if self.tcpReader.getData(datagram):
data = DatagramIterator(datagram)
opcode = data.getUint8()
else:
data = None
#.........这里部分代码省略.........
示例12: MyApp
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class MyApp(ShowBase):
uname = None
def __init__(self):
ShowBase.__init__(self)
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
host = "localhost";
port = 6002;
self.connection = self.cManager.openTCPClientConnection(host, port, 10000)
self.received = 1
if self.connection:
self.cReader.addConnection(self.connection)
#taskMgr.add(self.updateRoutine, 'updateRoutine')
# LOGIN Request Starts
self.uname = raw_input('Enter username :')
self.password= raw_input('Enter password :')
MyApp.uname = self.uname
#taskMgr.add(self.communicate101,'Login')
if(self.received):
print "->Client request:"
# Send a request to the server
myPyDatagram101 = PyDatagram()
prot = 101
myPyDatagram101.addUint16(prot)
myPyDatagram101.addString(self.uname)
myPyDatagram101.addString(self.password)
self.cWriter.send(myPyDatagram101,self.connection)
self.received = 0
taskMgr.add(self.receiveResponse101,'Login')
def sendRequest101(self):
if(self.received):
print "->Client request:"
# Send a request to the server
myPyDatagram101 = PyDatagram()
prot = 101
myPyDatagram101.addUint16(prot)
myPyDatagram101.addString(self.uname)
myPyDatagram101.addString(self.password)
self.cWriter.send(myPyDatagram101,self.connection)
self.received = 0
def receiveResponse101(self,task):
while self.cReader.dataAvailable():
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
self.myIterator = PyDatagramIterator(datagram)
print "<-Server response:"
print self.myIterator.getUint16()
self.msg = self.myIterator.getUint32()
self.l = self.myIterator.getUint32()
if self.msg is not None:
if self.l is not 0:
for x in range(0,self.l):
print self.myIterator.getString()
print self.myIterator.getUint32()
print self.myIterator.getUint32()
print self.msg, " received"
#raw_input("Press Enter to continue...")
self.received = 0
taskMgr.remove('Login')
#1-Character creatopm
#taskMgr.add(self.sendRequest104, 'CharacterCreation')
#2-heartbeat of playgame after login
MyApp.sendRequest113(self)
return task.again
# LOGIN Request End
# CHARACTER CREATION Starts
def sendRequest104(self,task):
if(self.received):
print "->Client request:"
# Send a request to the server
myPyDatagram = PyDatagram()
prot = 104
cname = raw_input('Character Name :')
faction_id_104 = raw_input('press 0 for Red Or 1 for Blue ? :')
classType_104 = raw_input('press 0 for Axe Or 1 for Sword ? :')
myPyDatagram.addUint16(prot)
myPyDatagram.addString(cname)
#.........这里部分代码省略.........
示例13: OldNetworkSystem
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class OldNetworkSystem(sandbox.EntitySystem):
def init(self, port=1999, backlog=1000, compress=False):
log.debug("Initing Network System")
self.accept("broadcastData", self.broadcastData)
self.port = port
self.backlog = backlog
self.compress = compress
self.cManager = QueuedConnectionManager()
self.cReader = QueuedConnectionReader(self.cManager, 0)
#self.cReader.setRawMode(True)
self.cWriter = ConnectionWriter(self.cManager, 0)
self.udpSocket = self.cManager.openUDPConnection(self.port)
self.cReader.addConnection(self.udpSocket)
self.activePlayers = [] # PlayerComponent
self.activeConnections = {} # {NetAddress : PlayerComponent}
self.lastAck = {} # {NetAddress: time}
self.startPolling()
self.accept("shipGenerated", self.shipGenerated)
def startPolling(self):
#taskMgr.add(self.tskReaderPolling, "serverListenTask", -40)
taskMgr.doMethodLater(10, self.activeCheck, "activeCheck")
#def tskReaderPolling(self, taskdata):
def begin(self):
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):
myIterator = PyDatagramIterator(datagram)
msgID = myIterator.getUint8()
#If not in our protocol range then we just reject
if msgID < 0 or msgID > 200:
return
self.lastAck[datagram.getAddress()] = datetime.datetime.now()
#TODO Switch to ip address and port
#Order of these will need to be optimized later
#We now pull out the rest of our headers
remotePacketCount = myIterator.getUint8()
ack = myIterator.getUint8()
acks = myIterator.getUint16()
hashID = myIterator.getUint16()
if msgID == protocol.LOGIN:
username = myIterator.getString()
password = myIterator.getString()
if username not in accountEntities:
entity = sandbox.createEntity()
component = AccountComponent()
component.name = username
component.passwordHash = password
if not accountEntities:
component.owner = True
component.address = datagram.getAddress()
entity.addComponent(component)
accountEntities[username] = entity.id
log.info("New player " + username + " logged in.")
#
self.activePlayers.append(component)
self.activeConnections[component.address] = component
ackDatagram = protocol.loginAccepted(entity.id)
self.sendData(ackDatagram, datagram.getAddress())
#TODO: Send initial states?
messenger.send("newPlayerShip", [component, entity])
else:
component = sandbox.entities[accountEntities[username]].get_component(AccountComponent)
if component.passwordHash != password:
log.info("Player " + username + " has the wrong password.")
else:
component.connection = datagram.getConnection()
log.info("Player " + username + " logged in.")
def activeCheck(self, task):
"""Checks for last ack from all known active conenctions."""
for address, lastTime in self.lastAck.items():
if (datetime.datetime.now() - lastTime).seconds > 30:
component = self.activeConnections[address]
#TODO: Disconnect
return task.again
def sendData(self, datagram, address):
self.cWriter.send(datagram, self.udpSocket, address)
def broadcastData(self, datagram):
# Broadcast data out to all activeConnections
#for accountID in accountEntities.items():
#sandbox.entities[accountID].get_component()
for addr in self.activeConnections.keys():
self.sendData(datagram, addr)
def processData(self, netDatagram):
myIterator = PyDatagramIterator(netDatagram)
return self.decode(myIterator.getString())
#.........这里部分代码省略.........
示例14: Connection
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
#.........这里部分代码省略.........
def registerRequest(self, username, password):
pkg = PyDatagram()
pkg.addUint16(103)
pkg.addString(username)
pkg.addString(password)
return pkg
def characterCreationRequest(self, username, classType):
pkg = PyDatagram()
pkg.addUint16(104)
pkg.addString(username)
pkg.addUint16(0)
pkg.addUint16(classType)
return pkg
def chatRequest(self, message):
pkg = PyDatagram()
pkg.addUint16(105)
pkg.addString(message)
return pkg
def moveRequest(self, x, y, z, h, isMoving):
pkg = PyDatagram()
pkg.addUint16(106)
pkg.addFloat32(x)
pkg.addFloat32(y)
pkg.addFloat32(z)
pkg.addFloat32(h)
pkg.addUint16(isMoving)
return pkg
def check(self):
while self.cReader.dataAvailable():
print "data here"
datagram = NetDatagram()
# Retrieve the contents of the datagram.
if self.cReader.getData(datagram):
data = PyDatagramIterator(datagram)
responseCode = data.getUint16()
print responseCode
if responseCode == 1:
self.getInt(data)
elif responseCode == 2:
self.getString(data)
elif responseCode == 3:
self.getShort(data)
elif responseCode == 4:
self.getFloat(data)
elif responseCode == 201:
self.getLogin(data)
elif responseCode == 203:
self.getRegistion(data)
elif responseCode == 204:
self.getCharacterCreation(data)
elif responseCode == 205:
self.getChat(data)
elif responseCode == 206:
self.getMove(data)
else:
print "nothing found"
def getInt(self, data):
msg = data.getInt32()
print "recieved ", msg
taskMgr.add(self.message, "message")
示例15: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import dataAvailable [as 别名]
class NetworkManager:
def __init__(self):
print "Network Manager Started"
def connection_open(self):
self.cManager = QueuedConnectionManager()
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager,0)
self.activeConnections=[] # We'll want to keep track of these later
self.cListener = QueuedConnectionListener(self.cManager, 0)
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)
print "Network Connection Opened"
taskMgr.add(self.tskListenerPolling,"Poll the connection listener",-39)
taskMgr.add(self.tskReaderPolling,"Poll the connection reader",-40)
def connection_close(self):
for aClient in self.activeConnections:
self.cReader.removeConnection(aClient)
self.activeConnections=[]
# close down our listener
self.cManager.closeConnection(self.tcpSocket)
print "Network Connection Closed"
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
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):
if base.client == True:
self.client_processing(datagram)
else:
self.server_processing(datagram)
return Task.cont
def server_messager(self,msg,args=[]):
if msg == "map_set":
order = PyDatagram()
order.addUint16(MAP_SET)
order.addInt32(args[0])
self.send_package(order)
elif msg == "client_update":
order = PyDatagram()
order.addUint16(CLIENT_INIT_UPDATE)
order.addString(args[0])
order.addString(args[1])
order.addInt32(args[2])
order.addInt32(args[3])
self.send_package(order)
elif msg == "chat_send":
r = args[0][0]
g = args[0][1]
b = args[0][2]
order = PyDatagram()
order.addUint16(SERVER_CHAT)
order.addInt32(r)
order.addInt32(g)
order.addInt32(b)
order.addString(args[1])
self.send_package(order)
base.menu_manager.menus["mp-game"].chat_add((r,g,b,1),args[1])
elif msg == "ready_button":
order = PyDatagram()
order.addUint16(SERVER_READY)
order.addInt32(args[0])
order.addInt32(args[1])
self.send_package(order)
base.menu_manager.menus["mp-game"].obj_list[args[0]]["indicatorValue"]=args[1]
base.menu_manager.menus["mp-game"].start_game_check()
elif msg == "server_loaded":
order = PyDatagram()
order.addUint16(SERVER_LOADED)
self.send_package(order)
elif msg == "all_loaded":
order = PyDatagram()
order.addUint16(ALL_LOADED)
self.send_package(order)
elif msg == "game_start":
order = PyDatagram()
order.addUint16(GAME_START)
self.send_package(order)
elif msg == "army_kill":
order = PyDatagram()
#.........这里部分代码省略.........