Exemple #1
0
    def stringReceived(self, string):
        # get the first byte, the packet type
        self.logger.debug("stringReceived: bytes: %d", len(string))
        (packetType,) = struct.unpack_from("!H", string, 0)
        self.logger.debug("packet type: %d, name: %s", packetType, TcpPacket.name(packetType))

        # find a handler to handle the real packet
        if not self.handlers.has_key(packetType):
            self.logger.error("invalid packet type: %d", packetType)
            self.transport.loseConnection()
            return

        # call the handler
        try:
            # call the handler, and strip out the first 2 bytes: the packet type
            self.handlers[packetType](string[2:])

            # update statistics
            self.statistics.tcpBytesReceived += len(string)
            self.statistics.tcpPacketsReceived += 1
            self.statistics.tcpLastR = datetime.datetime.now()
        except:
            self.logger.error("stringReceived: failed to execute handler for packet %d", packetType)
            self.transport.loseConnection()
            raise
Exemple #2
0
    def send(self, packetType, data=None):
        packetLength = 0

        if data != None:
            dataLength = len(data)
            packetLength = struct.calcsize("!H") + dataLength
            self.logger.debug("sending packet of type: %s, data length: %d", TcpPacket.name(packetType), dataLength)
            self.transport.write(struct.pack("!HH", packetLength, packetType))
            self.transport.write(data)

        else:
            self.logger.debug("sending empty packet of type: %s", TcpPacket.name(packetType))
            packetLength = struct.calcsize("!H")
            self.transport.write(struct.pack("!HH", packetLength, packetType))

        self.statistics.lock()
        self.statistics.tcpPacketsSent += 1
        self.statistics.tcpBytesSent += 2 + packetLength
        self.statistics.tcpLastSent = datetime.datetime.now()
        self.statistics.release()
Exemple #3
0
 def broadcast(self, packetType, data):
     """Send the packet to all clients."""
     dataLength = len(data)
     self.logger.debug(
         "broadcasting packet of type: %s, data length: %d to %d players",
         TcpPacket.name(packetType),
         dataLength,
         len(self.clients),
     )
     for clientId, client in self.clients.iteritems():
         client.send(packetType, data)