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


Python QueuedConnectionReader.addConnection方法代码示例

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


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

示例1: Login_Page

# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import addConnection [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  
开发者ID:burgui,项目名称:HW2,代码行数:104,代码来源:Login.py

示例2: TCP

# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import addConnection [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()
开发者ID:grimfang,项目名称:grim_net,代码行数:77,代码来源:TCP.py

示例3: __init__

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

示例4: World

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

示例5: World

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

示例6: TCP

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

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

示例7: login

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

#.........这里部分代码省略.........
开发者ID:jaimeh,项目名称:hw2-cs454,代码行数:103,代码来源:login.py

示例8: __init__

# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import addConnection [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
开发者ID:gaconkzk,项目名称:tethical,代码行数:65,代码来源:main.py

示例9: __init__

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

示例10: MyApp

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

示例11: OldNetworkSystem

# 需要导入模块: from panda3d.core import QueuedConnectionReader [as 别名]
# 或者: from panda3d.core.QueuedConnectionReader import addConnection [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)
开发者ID:croxis,项目名称:itf,代码行数:96,代码来源:client_net.py

示例12: SocketTCP

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

示例13: MyApp

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

示例14: OldNetworkSystem

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

示例15: Connection

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


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