def reader_polling(self, taskdata):

        if self.cReader.dataAvailable():
            datagram = NetDatagram(
            )  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                self.read_buffer = self.read_buffer + datagram.getMessage()
        while (True):
            if self.read_state == 0:
                if len(self.read_buffer) >= self.packet.header_length:
                    bytes_consumed = self.packet.header_length
                    self.packet.header = self.read_buffer[:bytes_consumed]
                    self.read_body_length = self.packet.decode_header()
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 1
                else:
                    break
            if self.read_state == 1:
                if len(self.read_buffer) >= self.read_body_length:
                    bytes_consumed = self.read_body_length
                    self.packet.data = self.read_buffer[:bytes_consumed]
                    self.packet.offset = 0
                    self.read_body_length = 0
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 0
                    self.new_data_callback(self.packet)

                else:
                    break
        return Task.cont
    def reader_polling(self, taskdata):

        if self.cReader.dataAvailable():
            datagram = NetDatagram()  # catch the incoming data in this instance
            # Check the return value; if we were threaded, someone else could have
            # snagged this data before we did
            if self.cReader.getData(datagram):
                self.read_buffer = self.read_buffer + datagram.getMessage()
        while (True):
            if self.read_state == 0:
                if len(self.read_buffer) >= self.packet.header_length:
                    bytes_consumed = self.packet.header_length
                    self.packet.header = self.read_buffer[:bytes_consumed]
                    self.read_body_length = self.packet.decode_header()
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 1
                else:
                    break
            if self.read_state == 1:
                if len(self.read_buffer) >= self.read_body_length:
                    bytes_consumed = self.read_body_length
                    self.packet.data = self.read_buffer[:bytes_consumed]
                    self.packet.offset = 0        
                    self.read_body_length = 0
                    self.read_buffer = self.read_buffer[bytes_consumed:]
                    self.read_state = 0
                    self.new_data_callback(self.packet)

                else:
                    break
        return Task.cont
Exemple #3
0
	def __handleDisconnect(self, data, msgID, client):
		''' Disconnect and send confirmation to the client.
			data (PyDatagramIterator): the list of data sent with this datagram
			msgID (Int): the message ID
			client (Connection): the connection that tendNehis datagram came from'''
		
		# Create a response
		pkg = NetDatagram()
		pkg.addUint16(MSG_DISCONNECT_RES)
		self._cWriter.send(pkg, client)
		
		# If user has joined a game, remove the player from that game
		for g in self.games:
			if g.isPlayerInGame(client):
				g.removePlayer(client)
		
		# If user is logged in disconnect
		username = ''
		for u in self.connectedUsers:
			if (u.connectedClient == client):
				username = u.username
				u.disconnect()
				self.connectedUsers.remove(u)
		
		# Delete client from list
		if client in self.connections:
			self.connections.remove(client)
			
		# Don't worry about pings any more
		if client in self.pingNonResponders:
			del(self.pingNonResponders[client])
		
		self._console.printNotice('%s: Disconnected user %s'%(client.getAddress().getIpString(),username))
Exemple #4
0
	def __sendGameListReq(self):
		''' Request a list of games on the connected server.'''
		
		# Send request
		if (self._connected and self._authorized):
			pkg = NetDatagram()
			pkg.addUint16(MSG_GAMELIST_REQ)
			self._cWriter.send(pkg, self._tcpSocket)
    def _debugSendMsg(msg):
        if not ClientMsg.myConnection:
            return

        print "DEBUG SEND MESSAGE:", msg
        datagram = NetDatagram()
        datagram.addString(pickle.dumps(msg, pickle.HIGHEST_PROTOCOL))
        ClientMsg.cWriter.send(datagram, ClientMsg.myConnection)
        ClientMsg.notify.debug("Client posted a message: %s", msg)
def eVV_VP_ACK_FAILED(ip, port):
    packet = SocketPacket()
    packet.add_int(VV_VP_ACK_FAILED)
    packet.add_string(ip)
    packet.add_int(port)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
def eVV_REQ_SIGNATURE(ip, port, object_id):
    packet = SocketPacket()
    packet.add_int(VV_REQ_SIGNATURE)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(object_id)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
def eVV_ACK_OK(ip, port, client_id):
    packet = SocketPacket()
    packet.add_int(VV_ACK_OK)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(client_id)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
def SendPacket(rpc, addr):
    global pq
    chance = random.random()
    p = rpc.CreateNewPacket(addr)
    rpc.SendPacket(p, addr)
    nd = NetDatagram()
    nd.appendData(p.GetDatagram().getMessage())#, p.GetDatagram().getLength())
    nd.setAddress(NetAddress())
    if(chance < 0.8):
        pq.append(nd)
        return nd
Exemple #10
0
	def shutdown(self):
		print('Shutting down server ...')
		
		# Send disconnect to all clients
		pkg = NetDatagram()
		pkg.addUint16(MSG_DISCONNECT_REQ)
		for c in self.connections:
			self._cWriter.send(pkg, c)
		self._cManager.closeConnection(self._tcpSocket)
		print('Server done')
		sys.exit()
def eVV_VP_ACK_OK(ip, port, cam_id):
    packet = SocketPacket()
    packet.add_int(VV_VP_ACK_OK)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(cam_id)  ## Added this
    packet.encode_header()

    datagram = NetDatagram()
    datagram.appendData("" + packet.get_header() + packet.get_body())
    return datagram
def eVV_READY(ip, port, vv_id):
    packet = SocketPacket()
    packet.add_int(VV_READY)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(vv_id)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
Exemple #13
0
	def __recievePingReq(self, data, msgID, client):
		''' Handle pings from the server.
			data (PyDatagramIterator): the list of data sent with this datagram
			msgID (Int): the message ID
			client (Connection): the connection that this datagram came from'''
		
		LOG.debug("Recieved a ping request")
		
		# Send response
		pkg = NetDatagram()
		pkg.addUint16(MSG_PING_RES)
		self._cWriter.send(pkg, self._tcpSocket)
Exemple #14
0
	def __sendJoinGameReq(self, id):
		''' Join a game on the server.
			id (int): the id of the game to join'''
			
		LOG.debug('Sending join game request')
		
		# Send Request
		if (self._connected and self._authorized):
			pkg = NetDatagram()
			pkg.addUint16(MSG_JOINGAME_REQ)
			pkg.addUint32(id)
			self._cWriter.send(pkg, self._tcpSocket)
Exemple #15
0
	def getData(self):
		data = []
		while self.cReader.dataAvailable():
			datagram = NetDatagram()  # catch the incoming data in this instance
			# Check the return value; if we were threaded, someone else could have
			# snagged this data before we did
			if self.cReader.getData(datagram):
				appendage={}
				appendage[0]=self.processData(datagram)
				appendage[1]=datagram.getConnection()
				data.append(appendage)
		return data
Exemple #16
0
	def __handlePingReq(self, data, msgID, client):
		''' Respond to a ping request.
			data (PyDatagramIterator): the list of data sent with this datagram
			msgID (Int): the message ID
			client (Connection): the connection that this datagram came from'''
		
		# Send response
		pkg = NetDatagram()
		pkg.addUint16(MSG_PING_RES)
		self._cWriter.send(pkg, client)
		
		self._console.printNotice('%s: Ping request'%(client.getAddress().getIpString()))
def eVV_CAM_MESSAGE(ip, port, cam_id, message):
    packet = SocketPacket()
    packet.add_int(VV_CAM_MESSAGE)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(cam_id)
    packet.add_packet(message)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
Exemple #18
0
 def getData(self):
     data = []
     while self.cReader.dataAvailable():
         datagram = NetDatagram(
         )  # catch the incoming data in this instance
         # Check the return value; if we were threaded, someone else could have
         # snagged this data before we did
         if self.cReader.getData(datagram):
             appendage = {}
             appendage[0] = self.processData(datagram)
             appendage[1] = datagram.getConnection()
             data.append(appendage)
     return data
def eVV_CAM_LIST(ip, port, cam_list):
    packet = SocketPacket()
    packet.add_int(VV_CAM_LIST)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(len(cam_list))
    for cam in cam_list:
      packet.add_int(cam)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
Exemple #20
0
	def _sendDownloadReq(type, id):
		''' Download a file from the server.'''
		
		LOG.debug("Downloading type=%s, id=%s"%(type, id))
		
		if (self._connected and self._authorized):
			pkg = NetDatagram()
			if (type == "MAP"):
				pkg.addUint16(MSG_DOWNLOADMAP_REQ)
				pkg.addUint32(id)
			elif (type == "UPDATE"):
				pkg.addUint16(MSG_DOWNLOADUPD_REQ)
				pkg.addUint32(id)
			self._cWriter.send(pkg, self._tcpSocket)
def eVV_REQ_VIDEO_ANALYSIS(ip, port, cam_id, width, height, jpeg):
    packet = SocketPacket()
    packet.add_int(VV_REQ_VIDEO_ANALYSIS)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(cam_id)
    packet.add_int(width)
    packet.add_int(height)
    packet.add_int(jpeg)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
    def _sendMsg(msg, sterner=False):
        if not ClientMsg.myConnection:
            return

        if not sterner:
            msg = (
                ClientMsg.game_id,
                ClientMsg.player_id,
            ) + msg

        datagram = NetDatagram()
        datagram.addString(pickle.dumps(msg, pickle.HIGHEST_PROTOCOL))
        ClientMsg.cWriter.send(datagram, ClientMsg.myConnection)
        ClientMsg.notify.debug("Client posted a message: %s", msg)
Exemple #23
0
	def __handleDownloadMap(data, msgID, client):
		''' Prepare and send requested map to client
			data (PyDatagramIterator): the list of data sent with this datagram
			msgID (Int): the message ID
			client (Connection): the connection that tendNehis datagram came from'''
		
		# Unpack message data
		id = data.getUint32()
		resp = 0
		
		filename = self._mapStore.getMap(id=id)['filename']
		mapString = self._mapStore.loadMapAsString(filename)
		
		if (mapString == None):
			LOG.debug('No such map')
			resp = 0
			mapString = ''
		else:
			LOG.debug('Sending map')
			resp = 1
			
		# Send response
		pkg = NetDatagram()
		pkg.addUint16(MSG_JOINGAME_RES)	
		pkg.addUint32(resp)
		pkg.addString(mapString)
		self._cWriter.send(pkg, client)
 def getData(self):
     data = []
     while self.cReader.dataAvailable():
         datagram = NetDatagram()  # catch the incoming data in this instance
         # Check the return value; if we were threaded, someone else could have
         # snagged this data before we did
         if self.cReader.getData(datagram):
             # pkg = []
             pkg = self._processData(datagram)
             tmpaddr = datagram.getAddress()
             addr = NetAddress()
             addr.setHost(tmpaddr.getIpString(), tmpaddr.getPort())
             pkg[ADDR] = addr
             data.append(pkg)
     return data
Exemple #25
0
 def TCPPacketListenTask(self, task):
     if self.tcpReader.dataAvailable():
         datagram = NetDatagram()
         if self.tcpReader.getData(datagram):
             data = PyDatagramIterator(datagram)
             ip = datagram.getAddress().getIpString()
             port = datagram.getAddress().getPort()
             peerAddr = NetAddress()
             peerAddr.setHost(ip, port)
             
             packetType = data.getUint8()
             if(packetType == Packet.PC_TCP_PACKET):
                 self.tcpPacketController.OnPacketReceived(data, peerAddr)
     
     return task.cont
def eVV_TRACK_SIGNATURE(ip, port, object_id, feature_str, sig):
    packet = SocketPacket()
    packet.add_int(VV_TRACK_SIGNATURE)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(object_id)
    packet.add_string(feature_str)
    packet.add_int(len(sig))
    for element in sig:
        packet.add_float(element)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
Exemple #27
0
	def getData(self):
		data = []
		for passed in self.passedData:
			data.append(passed)
			self.passedData.remove(passed)
		while self.cReader.dataAvailable():
			datagram = NetDatagram()
			if self.cReader.getData(datagram):
				if datagram.getConnection() in self.tempConnections:
					self.processTempConnection(datagram)
					continue
				for authed in self.users:
					if datagram.getConnection() == authed.connection:
						data.append((self.processData(datagram), datagram.getConnection()))
		return data
Exemple #28
0
	def __sendNewGameReq(self, gamename, mapID, numplayers):
		''' Create a new game on the server.
			name (String): the name of the game
			mapID (String): the MD5 ID of the map
			maxplayers (Int): the max players allowed'''
			
		LOG.debug('Sending new game request %s'%map)
		
		# Send Request
		if (self._connected and self._authorized):
			pkg = NetDatagram()
			pkg.addUint16(MSG_NEWGAME_REQ)
			pkg.addString(gamename)
			pkg.addString(mapID)
			pkg.addUint32(numplayers)
			self._cWriter.send(pkg, self._tcpSocket)
Exemple #29
0
 def getData(self):
     data = []
     while self.cReader.dataAvailable():
         datagram = NetDatagram()
         if self.cReader.getData(datagram):
             if datagram.getConnection() in self.tempConnections:
                 if self.auth(datagram):
                     self.tempConnections.remove(datagram.getConnection())
                 continue
             # Check if the data recieved is from a valid client.
             for client in self.activeClients:
                 if datagram.getConnection() == client.connection:
                     data.append(
                         ('client', self.processData(datagram), client))
                     break
             # Check if the data recieved is from a valid server.
             for server in self.activeServers:
                 if datagram.getConnection() == server.connection:
                     data.append(
                         ('server', self.processData(datagram), server))
                     break
             # Check if the data recieved is from a valid chat.
             for chat in self.activeChats:
                 if datagram.getConnection() == chat.connection:
                     data.append(('chat', self.processData(datagram), chat))
                     break
     return data
Exemple #30
0
	def __pingTask(self, Task):
		''' Ping all clients every PING_DELAY seconds to check for those who
			have dropped their connection.'''
		
		notice = 'Pinging: '
		
		for c in self.connections:
			# Don't ping connections we're still waiting on
			if c not in self.pingNonResponders.keys():
				notice = '%s%s '%(notice, c.getAddress().getIpString())
				self.pingNonResponders[c] = int(time.time())
				pkg = NetDatagram()
				pkg.addUint16(MSG_PING_REQ)
				self._cWriter.send(pkg, c)
		
		LOG.notice(notice)
		# Add task back into the taskmanager
		taskMgr.doMethodLater(PING_DELAY, self.__pingTask, 'serverPingTask', sort=-41)
def eVV_IMG(ip, port, cam_id, width, height, depth, color_code, jpeg, timestamp, image_data):
    packet = SocketPacket()
    packet.add_int(VV_IMG)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(cam_id)
    packet.add_int(width)
    packet.add_int(height)
    packet.add_int(depth)
    packet.add_char(color_code)
    packet.add_bool(jpeg)
    packet.add_double(timestamp)
    packet.add_string(image_data)
    packet.encode_header()

    datagram = NetDatagram()
    datagram.appendData("" + packet.get_header() + packet.get_body())
    return datagram
Exemple #32
0
	def __readTask(self, Task):
		''' This task listens for any messages coming in over any connections.
			If we get a connection passes it to the datagram handler.'''
		if self._cReader.dataAvailable():
			datagram=NetDatagram()
			if self._cReader.getData(datagram):
				data = PyDatagramIterator(datagram)
				msgID = data.getUint16()
			else:
				data = None
				msgID = MSG_NONE
		else:
			datagram = None
			data = None
			msgID = MSG_NONE
		if msgID is not MSG_NONE:
			self.__handleDatagram(data, msgID, datagram.getConnection())
		return Task.cont
Exemple #33
0
	def disconnect(self, callback):
		''' Disconnect from the server.
			
			callback (function): Funtion that will be called when a response is
				received. Callback will be passed one parameter (status)
					status = 1 if connection succeeded
					status = 0 if connection failed
		'''
		if self._connected:
			LOG.notice('Disconnecting...')
			pkg = NetDatagram()
			pkg.addUint16(MSG_DISCONNECT_REQ)
			self._cWriter.send(pkg, self._tcpSocket)
			self._cManager.closeConnection(self._tcpSocket)
			self._connected = False
			if callback != None: callback(1)
		else:
			LOG.error('Can not disconnect, we are not connected.')
			if callback != None: callback(0)
Exemple #34
0
 def getData(self):
     data = []
     for passed in self.passedData:
         data.append(passed)
         self.passedData.remove(passed)
     while self.cReader.dataAvailable():
         datagram = NetDatagram()
         if self.cReader.getData(datagram):
             data.append(self.processData(datagram))
     return data
def eVV_IMG(ip, port, cam_id, width, height, depth, color_code, jpeg, timestamp,
            image_data):
    packet = SocketPacket()
    packet.add_int(VV_IMG)
    packet.add_string(ip)
    packet.add_int(port)
    packet.add_int(cam_id)
    packet.add_int(width)
    packet.add_int(height)
    packet.add_int(depth)
    packet.add_char(color_code)
    packet.add_bool(jpeg)
    packet.add_double(timestamp)
    packet.add_string(image_data)
    packet.encode_header()
    
    datagram = NetDatagram()
    datagram.appendData('' + packet.get_header() + packet.get_body())
    return datagram
Exemple #36
0
	def __readTask(self, taskdata):
		''' This task listens for any messages coming in over any connections.
			If we get a connection passes it to the datagram handler.'''
		if self._cReader.dataAvailable():
			datagram=NetDatagram()  # catch the incoming data in this instance
			# Check the return value; if we were threaded, someone else could have
			# snagged this data before we did
			if self._cReader.getData(datagram):
				data = PyDatagramIterator(datagram)
				msgID = data.getUint16()
			else:
				data = None
				msgID = MSG_NONE
		else:
			datagram = None
			data = None
			msgID = MSG_NONE
		if msgID is not MSG_NONE:
			self.__handleDatagram(data, msgID, datagram.getConnection())
		return Task.cont
Exemple #37
0
	def __handleAuth(self, data, msgID, client):
		''' Try to authorize the connecting user, send the result.
			data (PyDatagramIterator): the list of data sent with this datagram
			msgID (Int): the message ID
			client (Connection): the connection that this datagram came from'''
		
		# Unpack message data
		username = data.getString()
		password = data.getString()
		auth = 0
		
		# Look for the username in the list of registered users
		for u in self.registeredUsers:
			if u.username == username:
				if u.connected:
					auth = 1
					self._console.printNotice('%s: User %s already connected'%(client.getAddress().getIpString(),username))
					break
				elif u.password != password:
					auth = 2
					self._console.printNotice('%s: User %s gave invalid password'%(client.getAddress().getIpString(),username))
					break
				else:
					auth = 3
					u.connect(client)
					self.connectedUsers.append(u)
					self._console.printNotice('%s: User %s connected with pass %s' %(client.getAddress().getIpString(),username,password))
		
		# Send response
		pkg = NetDatagram()
		pkg.addUint16(MSG_AUTH_RES)
		pkg.addUint32(auth)
		self._cWriter.send(pkg, client)
Exemple #38
0
	def __handleNewGame(self, data, msgID, client):
		''' Create a new game and respond with success or failure.
			data (PyDatagramIterator): the list of data sent with this datagram
			msgID (Int): the message ID
			client (Connection): the connection that tendNehis datagram came from'''
		
		# Unpack message data
		gameName    = data.getString()
		mapID       = data.getString()
		numPlayers  = data.getUint32()
		
		# If we do not have the map for the requested game tell client
		print("id=%s"%mapID)
		if(not self._mapStore.isAvailable(id=mapID)):
			response = 0
		else:
			# Create the game
			newGame = GameStateServer(gameName, numPlayers, mapID)
			if newGame is not None:
				self.games.append(newGame)
				response = newGame.id
			else:
				response = -1
		
		# Send response
		pkg = NetDatagram()
		pkg.addUint16(MSG_NEWGAME_RES)
		pkg.addInt32(response)
		self._cWriter.send(pkg, client)
		
		self._console.printNotice('%s: Request for new game: %s, %s, %d.' %(client.getAddress().getIpString(),gameName,mapID,numPlayers))