Esempio n. 1
0
class NetworkClient():
    def __init__(self):
        self.timeout = 3000

        self.c_manager = QueuedConnectionManager()
        self.c_reader = QueuedConnectionReader(self.c_manager, 0)
        self.c_writer = ConnectionWriter(self.c_manager, 0)

    def connect(self, ip, port):
        self.connection = self.c_manager.openTCPClientConnection(
            ip, port, self.timeout)
        if self.connection:
            self.c_reader.addConnection(self.connection)
            return (True)
        return (False)

    def disconnect(self):
        if self.connection:
            self.c_manager.closeConnection(self.connection)
        else:
            print("Trying to disconnect while not connected!")

    def send_data(self):
        data = PyDatagram()
        data.addString("Hello, world!")
        self.c_writer.send(data, self.connection)
Esempio n. 2
0
class Client(object):
    def __init__(self, host="localhost", port=5001, name="client"):
        self.name = name

        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.readerCallbacks = []

        taskMgr = Task.TaskManager()

        # how long until we give up trying to reach the server?
        timeout_in_miliseconds = 3000  # 3 seconds

        self.myConnection = self.cManager.openTCPClientConnection(
            host, port, timeout_in_miliseconds)
        if not self.myConnection:
            print("{}: Failed to connect to server!".format(self.name))
            return

        self.cReader.addConnection(
            self.myConnection)  # receive messages from server
        taskMgr.add(self.tskReaderPolling, "Poll the connection reader", -40)
        print("{}: Successfully connected to server {} at {}!".format(
            self.name, port, host))

    def tskReaderPolling(self, taskdata):
        # reader callback
        if not self.cReader.dataAvailable():
            return Task.cont

        # 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
        datagram = NetDatagram()
        if not self.cReader.getData(datagram):
            return Task.cont

        for callback in self.readerCallbacks:
            callback(datagram)

        return Task.cont

    def addReaderCallback(self, callbackFunction):
        self.readerCallbacks.append(callbackFunction)

    def ProcessReaderData(self, data):
        # TODO(vicdie): overwrite in derived classes
        pass

    def Close(self):
        # close connection if it exists
        if self.myConnection:
            self.cManager.closeConnection(self.myConnection)
Esempio n. 3
0
class Network():
	def __init__(self):
		self.c_manager = QueuedConnectionManager()
		self.c_listener = QueuedConnectionListener(self.c_manager, 0)
		self.c_reader = QueuedConnectionReader(self.c_manager, 0)
		self.c_writer = ConnectionWriter(self.c_manager,0)

		self.active_conns=[]

		self.port_address=9099 #No-other TCP/IP services are using this port
		self.backlog=1000 #If we ignore 1,000 connection attempts, something is wrong!

		#tcp_socket = c_manager.openTCPServerRendezvous(port_address,backlog)
		#self.tcp_socket = self.c_manager.openTCPServerRendezvous("0.0.0.0", 9099, 1000)
		#self.c_listener.addConnection(self.tcp_socket)

	def tsk_listener_pol(self, taskdata):
		if self.c_listener.newConnectionAvailable():

			rendezvous = PointerToConnection()
			netAddress = NetAddress()
			newConnection = PointerToConnection()

			if self.c_listener.getNewConnection(rendezvous,netAddress,newConnection):
				print("Connected: "+str(netAddress))
				newConnection = newConnection.p()
				self.active_conns.append(newConnection) # Remember connection
				self.c_reader.addConnection(newConnection)     # Begin reading connection
		return Task.cont

	def tsk_reader_pol(self, taskdata):
		if self.c_reader.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.c_reader.getData(datagram):
				self.data_process(datagram)
		return Task.cont

	def data_process(self, datagram):
			it = PyDatagramIterator(datagram)
			message = it.getString()
			print("Processed: "+message+" from: "+str(datagram.getAddress()))

	def listen(self):
		print("Now listening on all addresses on port 9099")
		self.tcp_socket = self.c_manager.openTCPServerRendezvous("0.0.0.0", 9099, 1000)
		self.c_listener.addConnection(self.tcp_socket)
		taskMgr.add(self.tsk_listener_pol, "Poll connection listener", -39)
		taskMgr.add(self.tsk_reader_pol, "Pol the connection reader", -40)

	def unlisten(self):
		print("Stopping listen")
		self.c_manager.closeConnection(self.tcp_socket)
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."""
        while self.cReader.dataAvailable():
            # Create a datagram to store all necessary data.
            datagram = NetDatagram()
            # Retrieve the contents of the datagram.
            if self.cReader.getData(datagram):
                # Prepare the datagram to be iterated.
                data = PyDatagramIterator(datagram)
                # Retrieve a "short" that contains the response code.
                responseCode = data.getUint16()
                # Pass into another method to execute the response.
                if responseCode != Constants.MSG_NONE:
                    self.handleResponse(responseCode, data)

        return task.cont

    def sendHeartbeat(self, task):
        if self.connection != None:
            self.sendRequest(Constants.C_HEARTBEAT)
        return task.again
Esempio n. 5
0
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():
            # Create a datagram to store all necessary data.
            datagram = NetDatagram()
            # Retrieve the contents of the datagram.
            if self.cReader.getData(datagram):
                # Prepare the datagram to be iterated.
                data = PyDatagramIterator(datagram)
                # Retrieve a "short" that contains the response code.
                responseCode = data.getUint16()
                # Pass into another method to execute the response.
                if responseCode != Constants.MSG_NONE:
                    self.handleResponse(responseCode, data)

        return task.cont
Esempio n. 6
0
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: "******"Enter password: "******"short" that contains the response code.
                responseCode = data.getUint16()
                # Pass into another method to execute the response.
                if responseCode != 0:
                    self.handleResponse(responseCode, data)

        return task.cont
Esempio n. 7
0
class Server:
    def __init__(self):

        self.port = 5555
        self.addr = "127.0.0.1"
        self.backlog = 7
        self.active_connections = dict()
        self.start = False

        self.connect()

    def connect(self) -> None:
        # Handle connections and terminations
        self.manager = QueuedConnectionManager()
        # Wait for clients connection requests
        self.listener = QueuedConnectionListener(self.manager, 0)
        # Buffers incoming data from active connection
        self.reader = QueuedConnectionReader(self.manager, 0)
        # Transmit PyDatagrams to active connection
        self.writer = ConnectionWriter(self.manager, 0)
        # Open TCP Rendezvous to accept client connections with a limit
        self.socket = self.manager.openTCPServerRendezvous(
            self.port, self.backlog)
        self.listener.addConnection(self.socket)
        print("Server listening on port %s...." % str(self.port))
        # Listen for mew incoming connections
        taskMgr.add(self.handle_incoming_connections,
                    "Poll the connection listener", -39)
        # Listen for new datagrams
        taskMgr.add(self.handle_connection_data,
                    "Poll the connection reader", -40)
        # Listen for dropped connections
        taskMgr.add(self.handle_dropped_connections,
                    "Poll the dropped connection listener", -41)
        # See if game can be started
        taskMgr.add(self.start_game, "Start Game", -42)

    def start_game(self, task_data: Task) -> Task:
        if len(self.active_connections) == self.backlog:
            self.start = True
        return Task.cont

    def handle_incoming_connections(self, task_data: Task) -> Task:
        if self.listener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            net_addr = NetAddress()
            new_connection = PointerToConnection()
            if self.listener.getNewConnection(rendezvous, net_addr, new_connection):
                new_connection = new_connection.p()
                # Keep track of our active connections
                self.active_connections[str(
                    new_connection.this)] = new_connection
                # Start reading the new connection
                self.reader.addConnection(new_connection)
                print("%s just connected" % str(new_connection))
        return Task.cont

    def handle_connection_data(self, task_data: Task) -> Task:
        if self.reader.dataAvailable():
            # Catch the incoming data
            datagram = NetDatagram()
            if self.reader.getData(datagram):
                name = self.handle_client_message(datagram)
                broadcast = f"Everyone, welcome {name} to the game!"
                self.broadcast_message(broadcast)

        return Task.cont

    def handle_dropped_connections(self, task_data: Task) -> Task:
        if self.manager.resetConnectionAvailable():
            connection_pointer = PointerToConnection()
            self.manager.getResetConnection(connection_pointer)
            lost_connection = connection_pointer.p()
            print("% s disconnected from server" % str(lost_connection))
            del self.active_connections[str(lost_connection.this)]
            self.manager.closeConnection(lost_connection)
        return Task.cont

    def handle_client_message(self, message: str) -> str:
        iterator = PyDatagramIterator(message)
        return iterator.getString()

    def get_connections_count(self) -> int:
        return len(self.active_connections)

    def send_personal_message(self, message: str, client: PointerToConnection) -> None:
        datagram = self.create_new_datagram(message)
        self.writer.send(datagram, client)

    def broadcast_message(self, message: str) -> None:
        datagram = self.create_new_datagram(message)
        for client in self.active_connections:
            self.writer.send(datagram, self.active_connections[client])

    def create_new_datagram(self, message: str) -> PyDatagram:
        new_datagram = PyDatagram()
        new_datagram.addString(message)
        return new_datagram

    def terminate_all_clients(self) -> None:
        for client in self.active_connections:
            self.reader.removeConnection(client)
        self.active_connections = list()

    def terminate_specific_client(self, client: PointerToConnection) -> None:
        self.reader.removeConnection(client)
        del self.active_connections[str(client)]
Esempio n. 8
0
class ConnectionManager:
    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.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 Main2 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-Main2')
            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(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():
            # Create a datagram to store all necessary data.
            datagram = NetDatagram()
            # Retrieve the contents of the datagram.
            if self.cReader.getData(datagram):
                # Prepare the datagram to be iterated.
                data = PyDatagramIterator(datagram)
                # Retrieve a "short" that contains the response code.
                responseCode = data.getUint16()
                # Pass into another method to execute the response.
                if responseCode != Constants.MSG_NONE:
                    self.handleResponse(responseCode, data)

        return task.cont
Esempio n. 9
0
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()
            order.addUint16(ARMY_KILL)
            order.addInt32(args[0])
            self.send_package(order)
        elif msg == "build_start":
            order = PyDatagram()
            order.addUint16(BUILD_START)
            order.addInt32(args[0])
            order.addInt8(args[1])
            order.addString(args[2])
            self.send_package(order)
        elif msg == "tower_capture":
            order = PyDatagram()
            order.addUint16(TOWER_CAPTURE)
            order.addInt32(args[0])
            order.addInt8(args[1])
            self.send_package(order)
        elif msg == "build_complete":
            order = PyDatagram()
            order.addUint16(BUILD_COMPLETE)
            order.addInt32(args[0])
            order.addInt8(args[1])
            order.addString(args[2])
            self.send_package(order)
        elif msg == "build_cancel":
            order = PyDatagram()
            order.addUint16(BUILD_CANCEL)
            order.addInt32(args[0])
            self.send_package(order)
        elif msg == "battle_start":
            order = PyDatagram()
            order.addUint16(BATTLE_START)
            order.addInt32(args[0])
            order.addFloat32(args[1])
            order.addFloat32(args[2])
            order.addInt32(args[3])
            order.addFloat32(args[4])
            order.addFloat32(args[5])
            order.addInt32(args[6])
            self.send_package(order)
        elif msg == "battle_clash":
            order = PyDatagram()
            order.addUint16(BATTLE_CLASH)
            order.addInt32(args[0])
            order.addInt32(args[1])
            order.addInt32(args[2])
            order.addString(args[3])
            order.addInt8(args[4])
            self.send_package(order)
        elif msg == "battle_turn":
            order = PyDatagram()
            order.addUint16(BATTLE_TURN)
            order.addInt32(args[0])
            order.addInt32(args[1])
            self.send_package(order)
        elif msg == "battle_end":
            order = PyDatagram()
            order.addUint16(BATTLE_END)
            order.addInt32(args[0])
            self.send_package(order)
        elif msg == "battle_armyadd":
            order = PyDatagram()
            order.addUint16(BATTLE_ARMYADD)
            order.addInt32(args[0])
            order.addInt32(args[1])
            order.addFloat32(args[2])
            order.addFloat32(args[3])
            self.send_package(order)


    def client_messager(self,msg,args=[]):
        if msg == "chat_send":
            order = PyDatagram()
            order.addUint16(CLIENT_CHAT)
            order.addInt32(args[0][0])
            order.addInt32(args[0][1])
            order.addInt32(args[0][2])
            order.addString(args[1])
            self.send_package(order)
        elif msg == "ready_button":
            order = PyDatagram()
            order.addUint16(CLIENT_READY)
            order.addInt32(args[0])
            order.addInt32(args[1])
            self.send_package(order)
        elif msg == "client_loaded":
            order = PyDatagram()
            order.addUint16(CLIENT_LOADED)
            self.send_package(order)
        elif msg == "game_init_request":
            order = PyDatagram()
            order.addUint16(CLIENT_INIT_REQUEST)
            order.addString(args[0])
            order.addString(args[1])
            self.send_package(order)
        elif msg == "build_start_request":
            order = PyDatagram()
            order.addUint16(BUILD_START_REQUEST)
            order.addInt32(args[0])
            order.addInt32(args[1])
            order.addString(args[2])
            self.send_package(order)
        elif msg == "build_cancel_request":
            order = PyDatagram()
            order.addUint16(BUILD_CANCEL_REQUEST)
            order.addInt32(args[0])
            self.send_package(order)

    def client_processing(self,datagram):
        data_iter = PyDatagramIterator(datagram)
        msgID = data_iter.getUint16()
        if msgID == PRINT_MESSAGE:
            messageToPrint = data_iter.getString()
            print messageToPrint
        if msgID == ARMY_MOVE:
            army_id = data_iter.getInt16()
            ax = data_iter.getFloat64()
            ay = data_iter.getFloat64()
            tx = data_iter.getFloat64()
            ty = data_iter.getFloat64()
            base.armies[army_id].node_path.setX(ax)
            base.armies[army_id].node_path.setY(ay)
            base.armies[army_id].move_to_point(tx,ty)
        if msgID == CLIENT_INIT_UPDATE:
            p1_name = data_iter.getString()
            p1_kingdom = data_iter.getString()
            p1_ready = data_iter.getInt32()
            game_map = data_iter.getInt32()
            base.menu_manager.menus["mp-game"].client_update(p1_name,p1_kingdom,p1_ready,game_map)
        if msgID == SERVER_CHAT:
            r = data_iter.getInt32()
            g = data_iter.getInt32()
            b = data_iter.getInt32()
            text = data_iter.getString()
            base.menu_manager.menus["mp-game"].chat_add((r,g,b),text)
        if msgID == SERVER_READY:
            but_id = data_iter.getInt32()
            state = data_iter.getInt32()
            base.menu_manager.menus["mp-game"].obj_list[but_id]["indicatorValue"]=state
            base.menu_manager.menus["mp-game"].start_game_check()
        if msgID == SERVER_LOADED:
            base.menu_manager.menus["mp-load"].load()
        if msgID == ALL_LOADED:
            base.menu_manager.menus["mp-load"].load_complete()
        if msgID == GAME_START:
            base.menu_manager.menu_goto("mp-load")
        if msgID == MAP_SET:
            map = data_iter.getInt32()
            base.menu_manager.menus["mp-game"].map_selected = map
            mapname = base.menu_manager.menus["mp-game"].maplist[map]["fullname"]
            mapimage = base.menu_manager.menus["mp-game"].maplist[map]["preview"]
            base.menu_manager.menus["mp-game"].obj_list[11]["text"]=mapname
            base.menu_manager.menus["mp-game"].obj_list[10].setImage(mapimage)
        if msgID == BATTLE_TURN:
            bat = data_iter.getInt32()
            turn = data_iter.getInt32()
            base.battles[bat].turn_change(turn)
        if msgID == BATTLE_START:
            a1 = data_iter.getInt32()
            a1_x = data_iter.getFloat32()
            a1_y = data_iter.getFloat32()
            a2 = data_iter.getInt32()
            a2_x = data_iter.getFloat32()
            a2_y = data_iter.getFloat32()
            army_start = data_iter.getInt32()
            base.armies[a1].stop()
            base.armies[a2].stop()
            base.armies[a1].node_path.setPos(a1_x,a1_y,0)
            base.armies[a2].node_path.setPos(a2_x,a2_y,0)
            base.battles.append(TimObjects.Battle([base.armies[a1],base.armies[a2]],army_start))
        if msgID == BATTLE_CLASH:
            battle = data_iter.getInt32()
            a1 = data_iter.getInt32()
            a2 = data_iter.getInt32()
            result = data_iter.getString()
            buff = data_iter.getInt8()
            base.battles[battle].clash(base.armies[a1],base.armies[a2],result,buff)
        if msgID == BATTLE_ARMYADD:
            bat = data_iter.getInt32()
            army = data_iter.getInt32()
            a_x = data_iter.getFloat32()
            a_y = data_iter.getFloat32()
            base.battles[bat].add_army(base.armies[army])
            base.armies[army].node_path.setPos(a_x,a_y,0)
        if msgID == BATTLE_END:
            bat = data_iter.getInt32()
            base.battles[bat].end()
        if msgID == BUILD_START:
            t_id = data_iter.getInt32()
            player = data_iter.getInt8()
            type = data_iter.getString()
            base.towers[t_id].build_start()
        if msgID == TOWER_CAPTURE:
            t_id = data_iter.getInt32()
            player = data_iter.getInt8()
            base.towers[t_id].change_owner(player)
        if msgID == BUILD_CANCEL:
            t_id = data_iter.getInt32()
            base.towers[t_id].build_cancel()
        if msgID == BUILD_COMPLETE:
            t_id = data_iter.getInt32()
            player = data_iter.getInt8()
            type = data_iter.getString()
            base.towers[t_id].create_counter()

    def server_processing(self,datagram):
        data_iter = PyDatagramIterator(datagram)
        msgID = data_iter.getUint16()
        if msgID == PRINT_MESSAGE:
            messageToPrint = data_iter.getString()
            print messageToPrint
        if msgID == ARMY_MOVE_REQUEST:
            army_id = data_iter.getInt16()
            ax = data_iter.getFloat64()
            ay = data_iter.getFloat64()
            tx = data_iter.getFloat64()
            ty = data_iter.getFloat64()
            base.armies[army_id].set_target(False,tx,ty)
        if msgID == CLIENT_CHAT:
            r = data_iter.getInt32()
            g = data_iter.getInt32()
            b = data_iter.getInt32()
            text = data_iter.getString()
            self.server_messager("chat_send",[(r,g,b),text])
            #base.main_menu.chat_add((r,g,b,1),text)
        if msgID == CLIENT_READY:
            but_id = data_iter.getInt32()
            state = data_iter.getInt32()
            self.server_messager("ready_button",[but_id,state])
            #base.main_menu.chat_add((r,g,b,1),text)
        if msgID == CLIENT_LOADED:
            self.server_messager("all_loaded",[])
            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
Esempio n. 10
0
class ClientServerBase(object):
    '''
    Baseclass for client and server, 
    these two have almost all functionality similar, except for who is responsible for opening / closing connections
    and the fact that server can have multiple connections
    '''
    def __init__(self, host="localhost", port=5001, name="client or server"):
        self.name = name
        self.port = port
        self.host = host

        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.connections = [
        ]  # list of connections, contains 1 item for client, multiple for server

        self.readerCallback = None  # will be called when a new message arrives
        self.writerCallback = None  # will be called when a message needs to be constructed

        self.taskMgr = Task.TaskManager()
        self.taskMgr.add(self.tskReaderPolling, "Poll the connection reader",
                         -40)
        self.taskMgr.add(self.tskWriterPolling, "Send data package", -39)

    def setReaderCallback(self, callbackFunction):
        self.readerCallback = callbackFunction

    def setWriterCallback(self, callbackFunction):
        self.writerCallback = callbackFunction

    def tskReaderPolling(self, taskdata):

        # reader callback
        if not self.cReader.dataAvailable():
            # print( "tskReaderPolling(): no data available!" )
            return Task.cont

        datagram = NetDatagram()
        if not self.cReader.getData(datagram):
            print("tskReaderPolling(): cannot claim data!")
            return Task.cont

        if self.readerCallback:
            print("tskReaderPolling():readerCallback()")
            self.readerCallback(datagram)

        return Task.cont

    def tskWriterPolling(self, data):

        if not self.writerCallback:
            return Task.cont

        data = self.writerCallback()
        if data == None:
            return Task.cont

        assert (isinstance(data, Datagram))

        print("tskWriterPolling() sending to : {}".format(len(
            self.connections)))

        for con in self.connections:
            if con:
                print("tskWriterPolling() sending")
                self.cWriter.send(data, con)

        return Task.cont

    def Close(self):
        # close each of the connections
        for c in self.connections:
            self.cManager.closeConnection(c)

    def ProcessReaderData(self, data):
        raise NotImplementedError(
            "overwrite ProcessReaderData() in client/server implementation")
Esempio n. 11
0
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

    def func1(self):
        self.clickedSubmit()
        self.createSelectionWindow()

    def clearPassText(self):
        self.passTextbox.enterText('')
    def clearUserText(self):
        self.userTextbox.enterText('')
    def getUserText(self):
        self.usernameInput = self.userTextbox.get()
    def getPassText(self):
        self.passwordInput = self.passTextbox.get()
    def setUserText(self, textEntered):
        print "username: "******"password: "******"" and self.passwordInput is not ""):
            print "You pressed Submit", self.usernameInput, " ; ",self.passwordInput
           # self.cManager.sendRequest(Constants.CMSG_AUTH, self.usernameInput+" "+self.passwordInput);

            login_info = self.usernameInput + " " + self.passwordInput
            request = self.loginRequest(login_info)
            self.cWriter.send(request,self.connection)
            self.createSelectionWindow()

        else:
            print "Please enter in a username and password"
    def clickedCancel(self):
        print "You pressed Cancel"
        exit()
    def clickedRegister(self):
        print "You pressed Register"
        self.createRegisterWindow()
    def clickedRegRegister(self):
        self.registerUsername = self.regInputUser.get()
        self.registerPassword = self.regInputPass.get()
        self.registerCPassword = self.regInputCPass.get()
        if self.registerPassword == self.registerCPassword:
            print "Success (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")"
            
            #self.cManager.sendRequest(Constants.CMSG_REGISTER, self.registerUsername+" "+self.registerPassword)
            register_info = self.registerUsername + " " + self.registerPassword
            request = self.registerRequest(register_info)
            self.cWriter.send(request,self.connection)
            self.createLoginWindow()
        else:
            self.failed = OnscreenText(text="Your password does not match Confirm Password.", pos=(-0.5, 0, 1), scale=0.06,fg=(1,0.5,0.5,1), align=TextNode.ACenter,mayChange=0)
            self.failed.reparentTo(self.frame)
            print "Failed (",self.registerUsername, ", ",self.registerPassword,", ",self.registerCPassword,")"
    def clickedRegCancel(self):
        self.destroyRegisterWindow()
        self.createLoginWindow()
    def destroyLoginWindow(self):
        self.frame.destroy()
        self.username.destroy()
        self.password.destroy()
        self.userTextbox.destroy()
        self.passTextbox.destroy()
        self.submitBtn.destroy()
        self.registerBtn.destroy()
        self.cancelBtn.destroy()
    def destroyRegisterWindow(self):
        self.frame.destroy()
        self.username.destroy()
        self.password.destroy()
        self.cpassword.destroy()
        self.regInputUser.destroy()
        self.regInputPass.destroy()
        self.regInputCPass.destroy()
        self.cancelBtn.destroy()
        self.registerBtn.destroy()
        self.failed.destroy();
    def createLoginWindow(self):
        self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-1, 1, -1, 1),#(Left,Right,Bottom,Top)
                                pos=(-0.5, 0, 0.5))
                
        self.username = OnscreenText(text = "username:"******"password: "******"" ,scale=.05,pos=(.1,0,0), command=self.setUserText,initialText="username", numLines = 1,focus=1,focusInCommand=self.clearUserText, focusOutCommand=self.getUserText)
        self.passTextbox = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.2),command=self.setPassText,initialText="password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
        self.userTextbox.reparentTo(self.frame)
        self.passTextbox.reparentTo(self.frame)
        self.submitBtn = DirectButton(text = ("Submit", "Login", "Submit", "disabled"), scale=.08, command=self.func1, pos=(0.8, 0.0, -0.90))
        self.registerBtn =  DirectButton(text = ("Register", "Register", "Register", "disabled"), scale=.075, command=self.clickedRegister, pos=(0.5, 0.0, -0.90))
        self.cancelBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedCancel, pos=(0.2, 0.0, -0.90))
        self.submitBtn.reparentTo(self.frame)
        self.cancelBtn.reparentTo(self.frame)
        self.registerBtn.reparentTo(self.frame)
    def createRegisterWindow(self):
        self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-1, 1, -1, 1),#(Left,Right,Bottom,Top)
                                pos=(-0.5, 0, 0.5))
        self.username = OnscreenText(text = "Username:"******"Password: "******"Confirm Password: "******"" ,scale=.05,pos=(.1,0,0), command=self.setUserText,initialText="username", numLines = 1,focus=1,focusInCommand=self.clearUserText, focusOutCommand=self.getUserText)
        self.regInputPass = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.2),command=self.setPassText,initialText="password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
        self.regInputCPass = DirectEntry(text = "" ,scale=.05,pos=(.1,0, -.4),command=self.setPassText,initialText="confirm password", numLines = 1,focus=0,focusInCommand=self.clearPassText, focusOutCommand=self.getPassText)
        self.regInputUser.reparentTo(self.frame)
        self.regInputPass.reparentTo(self.frame)
        self.regInputCPass.reparentTo(self.frame)
        self.registerBtn =  DirectButton(text = ("Register", "Register", "Register", "disabled"), scale=.075, command=self.clickedRegRegister, pos=(0.8, 0.0, -0.90))
        self.cancelBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedRegCancel, pos=(0.2, 0.0, -0.90))
        self.cancelBtn.reparentTo(self.frame)
        self.registerBtn.reparentTo(self.frame)

    def check(self):
		while self.cReader.dataAvailable():
			
			datagram = NetDatagram()
			# Retrieve the contents of the datagram.
			if self.cReader.getData(datagram):
                            
				data = PyDatagramIterator(datagram)
				responseCode = data.getUint16()
				
				if responseCode == 1:
					self.getInt(data)
				elif responseCode == 201: #login code
					if (self.getString(data)=="Unsuccessful login"): #appears if login unsuccessful
                                                print " "
                                                print "Unsuccessful login"
                                                print " "
                                                self.createLoginWindow()
                                        else:
                                                print "Your are logged in" #appear if login successful
                                                self.createLoginWindow()#appears the login options
                                                self.showRalph()      
				elif responseCode == 203: #register code
					if (self.getString(data)=="Registration successful"): #appear if registration was successful
                                                print "You are now registered"
                                                print "Please login" #user must login
                                                print " "
                                                self.createLoginWindow() 
                                        else:
                                                print " "#appear if registration wasn't successful
                                                print "Registration was unsuccessful. Pick a different username and please try again "
                                                print " "
                                                self.createLoginWindow()#user must attempt to register again
				elif responseCode == 4:
					self.getFloat(data)
				else:
					print "nothing found"

    def updateRoutine(self,task):
		self.check()
		return task.again;

    def checkConnection(self, task):

        if not self.cReader.isConnectionOk(self.connection):
            self.closeConnection()
            self.showDisconnected(0)

            return task.done

        return task.again

    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

    #function that unpackage the message from server
    def getString(self, data):
	msg = data.getString()
	return msg

    #package login request       
    def loginRequest(self, login_info):
		pkg = PyDatagram()
		pkg.addUint16(101)
		pkg.addString(login_info)
		return pkg
        #package register request
    def registerRequest(self, register_info):
		pkg = PyDatagram()
		pkg.addUint16(103)
		pkg.addString(register_info)
		return 

    def showRalph(self):
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0,0,0)

    #character Creation        
    def createCreateCharWindow(self):
        self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top)
                                pos=(-0.5, 0, 0.9))
        self.buttons = [
        DirectRadioButton(text = ' Sword ', variable=self.v, value=[0], scale=0.07, pos=(-0.4,0,0.32), command=self.setText),
        DirectRadioButton(text = ' Axe ', variable=self.v, value=[1], scale=0.07, pos=(0.2,0,0.32), command=self.setText)
        ]
 
        for button in self.buttons:
            button.setOthers(self.buttons)
        
        self.nameOfChar = OnscreenText(text = "Name The Character :", pos = (-0.2, -0.75), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.nameOfChar.reparentTo(self.frame)    
        self.nameOfCharTextbox = DirectEntry(text = "" ,scale=.07,pos=(0.25,0, -.75),command=self.setnameOfChar,initialText="name of character", numLines = 1,focus=0,focusInCommand=self.clearnameOfChar, focusOutCommand=self.getnameOfChar)
        self.nameOfCharTextbox.reparentTo(self.frame)   
        
        self.factionSelection = OnscreenText(text = "Faction Selection :", pos = (-0.15, -0.95), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.factionSelection.reparentTo(self.frame)
        
        self.factionBtns = [
        DirectRadioButton(text = ' Blue ', variable=self.v1, value=[0], scale=0.07, pos=(-0.05,0,-0.05), command=self.setfaction),
        DirectRadioButton(text = ' Red ', variable=self.v1, value=[1], scale=0.07, pos=(0.3,0,-0.05), command=self.setfaction)
        ]
         
        for button1 in self.factionBtns:
            button1.setOthers(self.factionBtns)
        self.okForCreateBtn = DirectButton(text = ("Ok", "Ok", "Ok", "disabled"), scale=.08, command=self.clickedOkForCreateBtn, pos=(-0.05, 0.0, -1.25))
        self.cancelForCreateBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedCancelForCreateBtn, pos=(0.4, 0.0, -1.25))
        self.okForCreateBtn.reparentTo(self.frame)
        self.cancelForCreateBtn.reparentTo(self.frame)
        
    def destroyCreateCharWindow(self):
        self.frame.destroy()
        self.nameOfChar.destroy()
        self.nameOfCharTextbox.destroy()
        self.factionSelection.destroy()
        self.okForCreateBtn.destroy()
        self.cancelForCreateBtn.destroy()
                                
    def clearnameOfChar(self):
        self.nameOfCharTextbox.enterText('')
        
    def getnameOfChar(self):
        self.nameOfCharInput = self.nameOfCharTextbox.get()
    
    def setnameOfChar(self, textEntered):
        print "name Of Char: ",textEntered
        self.nameOfChar = textEntered
        
    def clickedOkForCreateBtn(self):
        print "you have pressed the ok button for creating a character"
     
    def clickedCancelForCreateBtn(self):
        print "you have press the cancel button from the create character frame"
        self.destroyCreateCharWindow()
        self.createSelectionWindow()    
    
    def setText(status=None):
        bk_text = "CurrentValue "
        
    def setfaction(status=None):
        bk_text = "CurrentValue "    
        
    #character deletion        
    def createDeleteCharWindow(self):
        self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top)
                                pos=(-0.5, 0, 0.9))
        
        self.selectCharactertodelete = OnscreenText(text = "Select Character :", pos = (-0.02, -0.35), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.selectCharactertodelete.reparentTo(self.frame)
        self.selectCharacterToDeleteTextbox = DirectEntry(text = "" ,scale=.07,pos=(0.45,0, -.35),command=self.setselectCharacterToDelete,initialText="name of character", numLines = 1,focus=0,focusInCommand=self.clearselectCharacterToDelete, focusOutCommand=self.getselectCharacterToDelete)
        self.selectCharacterToDeleteTextbox.reparentTo(self.frame)
        self.referenceForDeletion = OnscreenText(text = "Reference to Character List:", pos = (-0.15, -0.75), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.referenceForDeletion.reparentTo(self.frame)
        self.deleteScrolledList = DirectScrolledList(
        decButton_pos= (0.35, 0, 0.53),
        decButton_text = "Dec",
        decButton_text_scale = 0.04,
        decButton_borderWidth = (0.005, 0.005),
 
        incButton_pos= (0.35, 0, -0.02),
        incButton_text = "Inc",
        incButton_text_scale = 0.04,
        incButton_borderWidth = (0.005, 0.005),
        
        
        pos = (0.7, 0, -0.99),
        numItemsVisible = 4,
        forceHeight = .11,
        itemFrame_frameSize = (-0.6, 0.6, -0.37, 0.11),
        itemFrame_pos = (0.35, 0, 0.4))
        
        for playerchar in ['xxxbluesword', 'xxxblueaxe', 'xxxredsword', 'xxxredsword01','xxx_red_sword04']:
            l = DirectLabel(text = playerchar, text_scale=0.1)
            self.deleteScrolledList.addItem(l)
            
        self.deleteScrolledList.reparentTo(self.frame)
        self.deleteBtn = DirectButton(text = ("Delete", "Delete", "Delete", "disabled"), scale=.08, command=self.clickedDelete, pos=(-0.2, 0.0, -1.25))
        
        self.delCancelBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedDelCancel, pos=(0.3, 0.0, -1.25))
        self.deleteBtn.reparentTo(self.frame)
        self.delCancelBtn.reparentTo(self.frame)
        
    def destroyDeleteCharWindow(self):
        self.frame.destroy()
        self.selectCharactertodelete.destroy()
        self.deleteBtn.destroy()
        self.delCancelBtn.destroy()
        self.selectCharacterToDeleteTextbox.destroy()
        self.referenceForDeletion.destroy()
        
    def clearselectCharacterToDelete(self):
        self.selectCharacterToDeleteTextbox.enterText('')
        
    def getselectCharacterToDelete(self):
        self.selectCharacterToDeleteInput = self.nameOfCharTextbox.get()
    
    def setselectCharacterToDelete(self, textEntered):
        print "name Of Char: ",textEntered
        self.selectCharacterToDelete = textEntered
        
    def clickedDelete(self):
        print "You pressed delete a character"
        
    def clickedDelCancel(self):
        print "to go back to slection menu"
        self.destroyDeleteCharWindow()
        self.createSelectionWindow()
            
    
    #character Selection
    def createSelectionWindow(self):
        self.frame = DirectFrame(frameColor=(0, 0, 0, 1), #(R,G,B,A)
                                frameSize=(-3, 3, -3, 3),#(Left,Right,Bottom,Top)
                                pos=(-0.5, 0, 0.9))
                
        self.createCharacter = DirectButton(text = ("Create Character","Create Character","Create Character","disabled"), scale=.08, command = self.clickedCreateChar, pos=(-0.14,0.0,-0.25))
        self.deleteCharacter = DirectButton(text = ("Delete Character","Delete Character","Delete Character","disabled"), scale=.08, command = self.clickedDeleteChar, pos=(-0.14,0.0,-0.40))
        self.createCharacter.reparentTo(self.frame)
        self.deleteCharacter.reparentTo(self.frame)
        self.selectCharacter = OnscreenText(text = "Select Character :", pos = (-0.12, -0.55), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.selectCharacter.reparentTo(self.frame)
        
        self.myScrolledList = DirectScrolledList(
        decButton_pos= (0.35, 0, 0.53),
        decButton_text = "Dec",
        decButton_text_scale = 0.04,
        decButton_borderWidth = (0.005, 0.005),
 
        incButton_pos= (0.35, 0, -0.02),
        incButton_text = "Inc",
        incButton_text_scale = 0.04,
        incButton_borderWidth = (0.005, 0.005),
 
        
        pos = (0.05, 0, -0.3),
        numItemsVisible = 4,
        forceHeight = .11,
        itemFrame_frameSize = (-0.6, 0.6, -0.37, 0.11),
        itemFrame_pos = (0.35, 0, 0.4),
        )
        
        self.selectCharacterTextbox = DirectEntry(text = "" ,scale=.07,pos=(0.28,0, -.55),command=self.setselectCharacterTextbox,initialText="name of character", numLines = 1,focus=0,focusInCommand=self.clearselectCharacterTextbox, focusOutCommand=self.getselectCharacterTextbox)
        self.selectCharacterTextbox.reparentTo(self.frame)
        self.referenceForSeletion = OnscreenText(text = "Reference to Character List:\n that already exists", pos = (-0.30, -0.75), scale = 0.08,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=0)
        self.referenceForSeletion.reparentTo(self.frame)
      
        for playerchar in ['xxxbluesword', 'xxxblueaxe', 'xxxredsword', 'xxxredsword01','xxx_red_sword04']:
            l = DirectLabel(text = playerchar, text_scale=0.1)
            self.myScrolledList.addItem(l) 
        
        self.submitBtn = DirectButton(text = ("Start", "Start", "Start", "disabled"), scale=.08, command=self.clickedSubmit, pos=(-0.2, 0.0, -1.45))
        
        self.cancelBtn =  DirectButton(text = ("Cancel", "Cancel", "Cancel", "disabled"), scale=.08, command=self.clickedCancel, pos=(0.3, 0.0, -1.45))
        self.submitBtn.reparentTo(self.frame)
        self.cancelBtn.reparentTo(self.frame)
        
    def destroySelectionWindow(self):
        self.frame.destroy()
        self.selectCharacter.destroy()
        self.createCharacter.destroy()
        self.deleteCharacter.destroy()
        self.submitBtn.destroy()        
        self.cancelBtn.destroy()
    
    def clearselectCharacterTextbox(self):
        self.selectCharacterTextbox.enterText('')
        
    def getselectCharacterTextbox(self):
        self.selectCharacterTextbox = self.selectCharacterTextbox.get()
    
    def setselectCharacterTextbox(self, textEntered):
        print "name Of Char: ",textEntered
        self.selectCharacterTextbox = textEntered
        
    def clickedCreateChar(self):
        print "You pressed create a new character"
        self.destroySelectionWindow()
        self.createCreateCharWindow()  
    
    def clickedDeleteChar(self):
        print "You pressed delete a character"
        self.destroySelectionWindow()
        self.createDeleteCharWindow()  
        
    def clickedSubmit(self):
        print "you pressed start button"
  
    def clickedCancel(self):
        print "You pressed Cancel"
Esempio n. 12
0
class Server(object):

    # https://www.panda3d.org/manual/index.php/Client-Server_Connection

    def __init__(self, host="localhost", port=5001):
        taskMgr = Task.TaskManager()

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)
        self.activeConnections = []  # We'll want to keep track of these later
        self.readerCallbacks = []

        backlog = 1000  #If we ignore 1,000 connection attempts, something is wrong!
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener.addConnection(self.tcpSocket)

        taskMgr.add(self.tskListenerPolling, "Poll the connection listener",
                    -39)
        taskMgr.add(self.tskReaderPolling, "Poll the connection reader", -40)
        print("started server! ({} at {})".format(port, host))

    def Start(self):
        # derived servers can overwrite this function if needed
        pass

    def tskListenerPolling(self, taskdata):
        # listen for new connections
        # TODO(victor): what happens if a client shuts down?
        # print("server.tskListenerPolling()")
        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
                print("server: received new connection!")
        return Task.cont

    def tskReaderPolling(self, taskdata):
        # reader callback
        if not self.cReader.dataAvailable():
            return Task.cont

        # 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
        datagram = NetDatagram()
        if not self.cReader.getData(datagram):
            return Task.cont

        for callback in self.readerCallbacks:
            callback(datagram)

        return Task.cont

    def addReaderCallback(self, callbackFunction):
        self.readerCallbacks.append(callbackFunction)

    def BroadcastMessage(self, datagram):
        # send the same message to all clients
        for client in self.activeConnections:
            self.cWriter.send(datagram, client)

    def Close(self):
        # remove all clients
        for client in self.activeConnections:
            self.cReader.removeConnection(client)
            self.activeConnections = []

        # close down our listener
        self.cManager.closeConnection(self.tcpSocket)