本文整理汇总了Python中panda3d.core.QueuedConnectionManager.openTCPClientConnection方法的典型用法代码示例。如果您正苦于以下问题:Python QueuedConnectionManager.openTCPClientConnection方法的具体用法?Python QueuedConnectionManager.openTCPClientConnection怎么用?Python QueuedConnectionManager.openTCPClientConnection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类panda3d.core.QueuedConnectionManager
的用法示例。
在下文中一共展示了QueuedConnectionManager.openTCPClientConnection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class ConnectionManager:
def __init__(self, main):
#self.world = world
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
self.main = main
self.rqTable = ServerRequestTable()
self.rsTable = ServerResponseTable()
self.connection = None
def startConnection(self):
"""Create a connection with the remote host.
If a connection can be created, create a task with a sort value of -39
to read packets from the socket.
"""
try:
if self.connection == None:
self.connection = self.cManager.openTCPClientConnection(Constants.SERVER_IP,
Constants.SERVER_PORT,
1000)
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine-Connection', -39)
taskMgr.doMethodLater(5, self.checkConnection, 'checkConnection')
return True
except:
pass
return False
def closeConnection(self):
"""Close the current connection with the remote host.
If an existing connection is found, remove both the Main task, which
is responsible for the heartbeat, and the Connection task, which is
responsible for reading packets from the socket, then properly close
the existing connection.
"""
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 = {}):
"""Prepare a request packet to be sent.
If the following request code exists, create an instance of this
specific request using any extra arguments, then properly send it to
the remote host.
"""
if self.connection != None:
request = self.rqTable.get(requestCode)
if request != None:
request.set(self.cWriter, self.connection)
#print('requestCode:'+str(requestCode))
#print('args:'+str(args))
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 = self.rsTable.get(responseCode)
if response != None:
response.set(self.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 updateRoutine(self, task):
"""A once-per-frame task used to read packets from the socket."""
while self.cReader.dataAvailable():
#.........这里部分代码省略.........
示例2: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class ConnectionManager:
def __init__(self, main):
self.main = main
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
self.rqTable = ServerRequestTable()
self.rsTable = ServerResponseTable()
self.connection = None
def startConnection(self):
"""Create a connection with the remote host.
If a connection can be created, create a task with a sort value of -39
to read packets from the socket.
"""
if self.connection == None:
self.connection = self.cManager.openTCPClientConnection(Constants.SERVER_IP, Constants.SERVER_PORT, 1000)
if self.connection:
self.cReader.addConnection(self.connection)
return True
return False
def initTasks(self):
"""Initialize tasks to check on connection and send heartbeat.
This must be done here because in `Main` we do not initialize Panda3D
until after a connection is started. Thus, `taskMgr` is not defined
when `startConnection()` is called. We rely on the callee to also run
`initTasks()` after a successful connection is created.
"""
if self.connection != None:
taskMgr.add(self.updateRoutine, "updateRoutine-Connection")
taskMgr.doMethodLater(5, self.checkConnection, "checkConnection")
taskMgr.doMethodLater(1.0 / Constants.TICKRATE, self.sendHeartbeat, "sendHeartbeat")
def closeConnection(self):
"""Close the current connection with the remote host.
If an existing connection is found, remove both the Main task, which
is responsible for the heartbeat, and the Connection task, which is
responsible for reading packets from the socket, then properly close
the existing connection.
"""
if self.connection != None:
taskMgr.remove("updateRoutine-Connection")
taskMgr.remove("checkConnection")
self.cManager.closeConnection(self.connection)
self.connection = None
def sendRequest(self, requestCode, args={}):
"""Prepare a request packet to be sent.
If the following request code exists, create an instance of this
specific request using any extra arguments, then properly send it to
the remote host.
"""
if self.connection != None:
request = self.rqTable.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 = self.rsTable.get(responseCode)
if response != None:
response.set(self.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 updateRoutine(self, task):
"""A once-per-frame task used to read packets from the socket."""
#.........这里部分代码省略.........
示例3: Login_Page
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
#.........这里部分代码省略.........
p = boxloc + Vec3(-0.5, -0.4, 0)
self.statusText = OnscreenText(text = "", pos = p, scale = 0.05, fg = (1, 0, 0, 1), align=TextNode.ALeft)
# A simple text object that you can display an error/status messages
# to the user
def updateStatus(self, statustext):
self.statusText.setText(statustext)
# all this does is change the status text.
def composeStringMessage(self, msg):
myPyDatagram = PyDatagram()
myPyDatagram.addString(msg)
return myPyDatagram
def retrieveStringMessage(self,datagram):
myIterator = PyDatagramIterator(datagram)
msg = myIterator.getString()
print msg, " received"
def sendRequest(self):
if(self.received):
print "->Client request:"
# Send a request to the server
msg = self.usernameBox.get()+" "+self.passwordBox.get()
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):
self.retrieveStringMessage(datagram)
self.received = 1
def communicate(self):
#print "communicate"
self.sendRequest()
self.receiveResponse()
def updateRoutine(self,task):
self.communicate()
return task.again;
def attemptLogin(self):
# checks to make sure the user inputed a username and password:
# if they didn't it will spit out an error message
# if they did, it will try to connect to the login server
# (under construction)
if(self.usernameBox.get() == ""):
if(self.passwordBox.get() == ""):
self.updateStatus("ERROR: You must enter a username and password before logging in.")
else:
self.updateStatus("ERROR: You must specify a username")
self.passwordBox['focus'] = 0
self.usernameBox['focus'] = 1
elif(self.passwordBox.get() == ""):
self.updateStatus("ERROR: You must enter a password")
self.usernameBox['focus'] = 0
self.passwordBox['focus'] = 1
else:
self.updateStatus("Attempting to login...")
print "Attempting to connect to Server with credentials: (" + self.usernameBox.get() + ", " + self.passwordBox.get() + ")"
# this is where the networking code will get put in
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
HOST = "localhost";
PORT = 1234;
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.doMethodLater(3, self.updateRoutine, 'updateRoutine')
def cycleLoginBox(self):
# function is triggered by the tab key so you can cycle between
# the two input fields like on most login screens
# IMPORTANT: When you change the focus to one of the text boxes,
# you have to unset the focus on the other textbox. If you do not
# do this Panda seems to get confused.
if(self.passwordBox['focus'] == 1):
self.passwordBox['focus'] = 0
self.usernameBox['focus'] = 1
elif(self.usernameBox['focus'] == 1):
self.usernameBox['focus'] = 0
self.passwordBox['focus'] = 1
示例4: Connection
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class Connection(ShowBase):
def __init__(self):
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
try:
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')
except:
pass
# 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 loginRequest(self, username, password):
pkg = PyDatagram()
pkg.addUint16(101)
pkg.addString(username)
pkg.addString(password)
return pkg
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)
#.........这里部分代码省略.........
示例5: TCP
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [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()
示例6: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class client:
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.connection = None
def startConnection(self):
"""Create a connection with the remote host.
If a connection can be created, create a task with a sort value of -39
to read packets from the socket.
"""
try:
if self.connection == None:
self.connection = self.cManager.openTCPClientConnection('localhost',
9090,
1000)
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine-Connection', -39)
taskMgr.doMethodLater(5, self.checkConnection, 'checkConnection')
return True
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:
#.........这里部分代码省略.........
示例7: World
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class World(DirectObject):
def __init__(self):
self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
self.opponents = dict()
self.logStat = -1
self.id = 0
self.username = ""
host = "localhost"
port = 9252
self.connection = self.cManager.openTCPClientConnection(host, port, 10000)
self.received = 1
self.playersText = []
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine')
taskMgr.add(self.login, 'login')
taskMgr.doMethodLater(.1, self.heartbeat, 'heartbeat')
# Replace with actual, dynamic list of players from the server
self.players = dict()
# Placeholder, replace with actual # of players later
self.numberOfPlayers = 2
# Stores the OnScreenText for each player in the players list
# Populated and depopulated using listPlayers and delistPlayers
self.playersText = []
# Stores all the player objects currently logged in
self.playerObjects = []
base.win.setClearColor(Vec4(0,0,0,1))
# Post the instructions
#self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
#self.inst1 = addInstructions(0.95, "[ESC]: Quit")
#self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
#self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
#self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
#self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
#self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
#self.inst8 = addInstructions(0.60, "[Q]: Display List Of Connected Players")
# Set up the environment
#
# This environment model contains collision meshes. If you look
# in the egg file, you will see the following:
#
# <Collide> { Polyset keep descend }
#
# This tag causes the following mesh to be converted to a collision
# mesh -- a mesh which is optimized for collision, not rendering.
# It also keeps the original mesh, so there are now two copies ---
# one optimized for rendering, one for collisions.
self.environ = loader.loadModel("models/world")
self.environ.reparentTo(render)
self.environ.setPos(0,0,0)
# Create the main character, Ralph
ralphStartPos = self.environ.find("**/start_point").getPos()
self.ralph = Actor("models/ralph",
{"run":"models/ralph-run",
"walk":"models/ralph-walk"})
self.ralph.reparentTo(render)
self.ralph.setScale(.2)
self.ralph.setPos(ralphStartPos)
ralphStartPos.setY(ralphStartPos.getY()-10)
self.ralph.setPos(ralphStartPos.getX(),ralphStartPos.getY(),ralphStartPos.getZ())
self.initx = ralphStartPos.getX()
# Add our Ralph to list to Ralphs
self.playerObjects.append(self.ralph)
# Load and transform the panda actor.
self.pandaActor = Actor("models/panda-model",
{"walk": "models/panda-walk4"})
self.pandaActor.setScale(0.003, 0.003, 0.003)
self.pandaActor.reparentTo(render)
# Loop its animation.
#self.pandaActor.loop("walk")
self.pandaActor.setPos(ralphStartPos.getX(),ralphStartPos.getY()-20,ralphStartPos.getZ())
#.........这里部分代码省略.........
示例8: World
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class World(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)
host = "localhost"
port = 9898
self.connection = self.cManager.openTCPClientConnection(host, port, 10000)
#self.received = 1
#store a dictionary of active players with username player as key value pair
#the dictionary also contain a special player named panda
self.players = {}
#for display the list on the screen
self.temp = []
#store a dictionary of playerObject
self.playerObjects = {}
self.render = render
self.loginSuccessful = False
self.isMoving = False
self.justStoping = False
self.targetPlayer = None
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine')
#taskMgr.doMethodLater(0.5, self.updateRoutine, 'updateRoutine')
#taskMgr.add(self.updatePandaAttack, 'updatePandaAttack')
#taskMgr.doMethodLater(3, self.updatePandaAttack, 'updatePandaAttack')
self.loginRegister()
#################Communication Method################
def loginRegister(self):
print "1. Login"
print "2. Register"
userInput = str(raw_input("Enter 1 or 2: "))
if userInput == "1":
self.login()
elif userInput == "2":
self.register();
else:
print "Invalid input"
self.loginRegister()
def register(self):
print "Please enter your username: "
username = str(raw_input())
print "Please enter your password: "
password = str(raw_input())
msg = "{} {} {}".format(REGISTER, username, password)
self.sendRequest(msg)
#define self.username to specify the username for this object
def login(self):
print "Please enter your username: "
self.username = str(raw_input())
print "Please enter your password: "
password = str(raw_input())
msg = "{} {} {}".format(LOGIN, self.username, password)
self.sendRequest(msg)
#user need to press esc key to logout
def logout(self, x, y, z, h):
print "logout called"
player = self.players[self.username]
msg = "{} {},{},{},{},{}".format(LOGOUT, self.username,
player.getX(), player.getY(), player.getZ(), player.getH())
print msg
self.sendRequest(msg)
sys.exit()
def updateMovement(self, isMove, x, y, z, h):
#send code username,ismove,x,y,z,h to the server according to the protocol
msg = "{} {},{},{},{},{},{}".format(UPDATE_PLAYER_MOVE, self.username, isMove, x, y, z, h)
self.sendRequest(msg)
def possibleAttackRequest(self, distance):
msg = "{} {},{}".format(PANDA_ATTACK_REQUEST, self.username, distance)
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
#.........这里部分代码省略.........
示例9: MyApp
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [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')
print 'Hello You Are Now Connected To The Server'
#self.heartbeat()
self.options()
#options for the clients when game starts
def options(self):
self.option = 0
self.option = str(raw_input("Please Selection An Option\n1-Enter Chat\n2-Messages\n3-Quit\n"))
if self.option == "1":
self.chat()
if self.option == "2":
self.messages()
if self.option == "3":
sys.exit(0)
#function to chat
def chat(self):
self.username = ""
self.message = ""
self.username = str(raw_input("Please enter your username: "))
self.message = str(raw_input("Please enter your message: "))
chat_message = self.username + " " + self.message
request = self.chatRequest(chat_message)
self.cWriter.send(request,self.connection)
#package chat request
def chatRequest(self, chat_info):
pkg = PyDatagram()
pkg.addUint16(112)
pkg.addString(chat_info)
return pkg
#message options for the clients when game starts
def messages(self):
self.option = 0
self.option = str(raw_input("Please Selection An Option\n1-Send A Message\n2-Check Messages\n3-Return\n"))
if self.option == "1":
self.message()
if self.option == "2":
self.checkMessages()
if self.option == "3":
self.options()
#function to message
def checkMessages(self):
self.username = str(raw_input("Please enter your username: "))
chat_message = self.username
request = self.checkMessagesRequest(chat_message)
self.cWriter.send(request,self.connection)
#package message request
def checkMessagesRequest(self, chat_info):
pkg = PyDatagram()
pkg.addUint16(116)
pkg.addString(chat_info)
return pkg
#function to send a message
def message(self):
self.from_Username = ""
self.to_Username = " "
self.message = ""
self.from_Username = str(raw_input("Please enter your username: "))
self.to_Username = str(raw_input("Please enter which username you want to send the message: "))
self.message = str(raw_input("Please enter your message: "))
chat_message = self.from_Username + " " +self.to_Username+ " " + self.message
request = self.messageRequest(chat_message)
self.cWriter.send(request,self.connection)
#package message request
def messageRequest(self, chat_info):
pkg = PyDatagram()
#.........这里部分代码省略.........
示例10: Connection
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [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()
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
#.........这里部分代码省略.........
base.menu_manager.menus["mp-load"].load_complete()
if msgID == CLIENT_INIT_REQUEST:
pn = data_iter.getString()
pk = data_iter.getString()
base.menu_manager.menus["mp-game"].obj_list[6]["text"] = pn
base.menu_manager.menus["mp-game"].obj_list[7]["text"] = pk
self.server_messager("client_update",[base.menu_manager.menus["mp-game"].obj_list[4]["text"],
base.menu_manager.menus["mp-game"].obj_list[5]["text"],
base.menu_manager.menus["mp-game"].obj_list[8]["indicatorValue"],
base.menu_manager.menus["mp-game"].map_selected])
if msgID == BUILD_START_REQUEST:
t_id = data_iter.getInt32()
player = data_iter.getInt32()
type = data_iter.getString()
base.towers[t_id].build_start()
if msgID == BUILD_CANCEL_REQUEST:
t_id = data_iter.getInt32()
player = data_iter.getInt32()
type = data_iter.getString()
base.towers[t_id].build_cancel()
def msgAllClients(self):
myPyDatagram=self.myNewPyDatagram() # build a datagram to send
for aClient in self.activeConnections:
self.cWriter.send(myPyDatagram,aClient)
def send_package(self,package):
# print "packaged"
for aClient in self.activeConnections:
print "Package",package,"sent"
self.cWriter.send(package,aClient)
def army_move(self,army_id,tx,ty):
order = PyDatagram()
if base.client == True:
order.addUint16(ARMY_MOVE_REQUEST)
else:
order.addUint16(ARMY_MOVE)
ax = base.armies[army_id].node_path.getX()
ay = base.armies[army_id].node_path.getY()
order.addInt16(army_id)
order.addFloat64(ax)
order.addFloat64(ay)
order.addFloat64(tx)
order.addFloat64(ty)
if base.client == True:
self.cWriter.send(order,base.server_connection)
else:
self.send_package(order)
base.armies[army_id].move_to_point(tx,ty)
def tower_train(self,tower_id,build_object):
order = PyDatagram()
if base.client == True:
order.addUint16(REQUEST_TOWER_TRAIN)
else:
order.addUint16(TOWER_TRAIN)
order.addInt16(army_id)
order.addFloat64(tx)
order.addFloat64(ty)
if base.client == True:
self.cWriter.send(order,base.server_connection)
else:
self.send_package(order)
base.towers[tower_id].train_counter()
# def request_army_move(self,army_id,tx,ty):
# order = PyDatagram()
# order.addUint16(REQUEST_MOVE_COUNTER)
# order.addInt16(army_id)
# order.addFloat64(tx)
# order.addFloat64(ty)
# self.cWriter.send(order,base.server_connection)
def myNewPyDatagram(self):
# Send a test message
myPyDatagram = PyDatagram()
myPyDatagram.addUint16(PRINT_MESSAGE)
myPyDatagram.addString("You got ze message!")
return myPyDatagram
def client_connect(self,ip):
port_address=9099 # same for client and server
# a valid server URL. You can also use a DNS name
# if the server has one, such as "localhost" or "panda3d.org"
ip_address=ip
# how long until we give up trying to reach the server?
timeout_in_miliseconds=3000 # 3 seconds
base.server_connection=self.cManager.openTCPClientConnection(ip_address,port_address,timeout_in_miliseconds)
if base.server_connection:
self.cReader.addConnection(base.server_connection) # receive messages from server
self.activeConnections.append(base.server_connection)
print "Connected to server",ip
return True
print "Connection failed"
return False
示例12: MyApp
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [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):
#.........这里部分代码省略.........
示例13: MyApp
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [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)
#.........这里部分代码省略.........
示例14: login
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [as 别名]
class login(DirectObject):
TEXT_COLOR = (1,1,1,1)
FONT_TYPE_01 = 0
TEXT_SHADOW_COLOR = (0,0,0,0.5)
usernameInput = ""
passwordInput = ""
frame = DirectFrame()
username = OnscreenText()
password = OnscreenText()
cpassword = OnscreenText()
failed = OnscreenText()
userTextbox = DirectEntry()
passTextbox = DirectEntry()
submitBtn = DirectButton()
registerBtn = DirectButton()
cancelBtn = DirectButton()
registerUsername = ""
registerPassword = ""
registerCPassword = ""
regInputUser = DirectEntry()
regInputPass = DirectEntry()
regInputCPass = DirectEntry()
regRegisterBtn = DirectButton()
regCancelBtn = DirectButton()
#character selection varaiables
createCharacter = DirectButton()
deleteCharacter = DirectButton()
selectCharacter = OnscreenText()
selectCharacterTextbox = DirectEntry()
selectCharacterInput=''
referenceForSelection = OnscreenText()
myScrolledList = DirectScrolledList()
submitBtn = DirectButton()
cancelBtn = DirectButton()
#character deletion varaiables
selectCharactertodelete = OnscreenText()
deleteBtn = DirectButton()
delCancelBtn = DirectButton()
CharacterToDeleteTextbox = DirectEntry()
referenceForDeletion = OnscreenText()
CharacterToDeleteInput = ' '
#character creation varaiables
v=[0]
v1=[0]
nameOfChar = OnscreenText()
nameOfCharTextbox = DirectEntry()
factionSelection = OnscreenText()
nameOfCharInput =''
def __init__(self):
print 'Loading Login...'
# self.cManager = ConnectionManager()
# self.startConnection()
self.cManager = QueuedConnectionManager()
self.cListener = QueuedConnectionListener(self.cManager, 0)
self.cReader = QueuedConnectionReader(self.cManager, 0)
self.cWriter = ConnectionWriter(self.cManager, 0)
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.connection = self.cManager.openTCPClientConnection(Constants.SERVER_IP,
Constants.SERVER_PORT,
1000)
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine-Connection', -39)
taskMgr.doMethodLater(5, self.checkConnection, 'checkConnection')
self.createLoginWindow()
def startConnection(self):
"""Create a connection to the remote host.
If a connection cannot be created, it will ask the user to perform
additional retries.
"""
if self.cManager.connection == None:
if not self.cManager.startConnection():
return False
return True
#.........这里部分代码省略.........
示例15: MyApp
# 需要导入模块: from panda3d.core import QueuedConnectionManager [as 别名]
# 或者: from panda3d.core.QueuedConnectionManager import openTCPClientConnection [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)
self.player = Player()
self.opponents = dict()
self.logStat = -1
host = "localhost"
port = 9252
self.connection = self.cManager.openTCPClientConnection(host, port, 10000)
self.received = 1
self.playersText = []
if self.connection:
self.cReader.addConnection(self.connection)
taskMgr.add(self.updateRoutine, 'updateRoutine')
taskMgr.add(self.login, 'login')
#taskMgr.doMethodLater(3, self.updateRoutine, 'updateRoutine')
taskMgr.doMethodLater(.1, self.heartbeat, 'heartbeat')
self.accept("q", self.listPlayers)
self.accept("q-up", self.delistPlayers)
self.accept("escape", self.disconnect)
self.accept("arrow_up", self.move)
def login(self, task):
self.option = 0
self.option = str(raw_input("1-Login\n2-Register\n"))
if self.option == "1":
un = str(raw_input("Username: "))
pw = str(raw_input("Password: "))
request = self.loginRequest(un, pw)
self.cWriter.send(request,self.connection)
taskMgr.remove('login')
elif self.option == "2":
un = str(raw_input("Username: "))
pw = str(raw_input("Password: "))
request = self.registerRequest(un, pw)
self.cWriter.send(request,self.connection)
taskMgr.remove('login')
def loginRequest(self, username, password):
pkg = PyDatagram()
pkg.addUint16(101)
pkg.addString(username)
pkg.addString(password)
return pkg
def registerRequest(self, username, password):
pkg = PyDatagram()
pkg.addUint16(102)
pkg.addString(username)
pkg.addString(password)
return pkg
def disconnect(self):
pkg = PyDatagram()
pkg.addUint16(119)
self.cWriter.send(pkg,self.connection)
sys.exit()
def move(self):
self.player.x += 1
pkg = PyDatagram()
pkg.addUint16(114)
pkg.addFloat32(self.player.x)
pkg.addFloat32(self.player.y)
pkg.addFloat32(self.player.z)
pkg.addFloat32(self.player.rotation)
self.cWriter.send(pkg,self.connection)
def movePlayer(self, data):
id = data.getInt32()
x = data.getFloat32()
y = data.getFloat32()
z = data.getFloat32()
rotation = data.getFloat32()
if self.player.id == id:
self.player.x = x
self.player.y = y
self.player.z = z
self.player.rotation = rotation
else:
self.opponents[id].x = x
self.opponents[id].y = y
self.opponents[id].z = z
self.opponents[id].rotation = rotation
def dropPlayer(self, data):
id = data.getInt32()
del self.opponents[id]
#.........这里部分代码省略.........