import struct import logging import gevent from gevent import socket from gevent import queue from gevent import event from gevent.select import select as gselect logger = logging.getLogger("Connection") class Connection(object): MAGIC = b'VT01' FMT = ' header_size: message_length, magic = struct.unpack_from(Connection.FMT, buf) if magic != Connection.MAGIC: logger.debug("invalid magic, got %s" % repr(magic)) self.disconnect() return packet_length = header_size + message_length if len(buf) < packet_length: return message = buf[header_size:packet_length] buf = buf[packet_length:] self.recv_queue.put(message) self._readbuf = buf class TCPConnection(Connection): def _new_socket(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def _connect(self, server_addr): self.socket.connect(server_addr) def _read_data(self): try: return self.socket.recv(16384) except socket.error: return '' def _write_data(self, data): self.socket.sendall(data) class UDPConnection(Connection): def _new_socket(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def _connect(self, server_addr): pass def _read_data(self): pass def _write_data(self, data): pass