import socket import select import logging from threading import Thread from .client import Client logger = logging.getLogger(__name__) class Server(Thread): BUFF_SIZE = 65535 def __init__(self, host, port): super(Server, self).__init__() self.daemon = True self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((self.host, self.port)) self.socket.setblocking(0) self.clients = {} def run(self): # Main server loop while True: (incomming, _, _) = select.select( [self.socket], [], [], 1) if incomming: data, addr = self.socket.recvfrom(self.BUFF_SIZE) if addr in self.clients: self.clients[addr].handle_data(data) else: try: self.clients[addr] = Client(self, addr) logger.info("Accepted connection from %s:%s" % (addr[0], addr[1])) self.clients[addr].handle_data(data) except socket.error: try: self.socket.close() except: pass logger.warn("Something went very wrong...") #exit() return clients = [x for x in self.clients.values() if x.get_buffer_size() > 0] for client in clients: client.write_socket() """for c in self.clients.values(): print(c.__writebuffer)""" def restart(self): [c.restart() for c in self.clients]