def connect(self): """Negotiate for connection to remote host.""" self.logger.info("Connecting to %s:%s." % self.addr) try: self.socket = create_connection(self.addr, 5) self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) except IOError as e: self.logger.critical("Connection failed: %s" % e) sys.exit(1) net.send(self.socket, 'icanhazconnectplz?', self.username) servername, response = net.receive(self.socket) if servername == None: self.logger.critical("Connection failed: Unknown reason") if 'accepted' not in response[0]: self.logger.critical("Bad server response") self.logger.debug("Data causing error:\n%s" % response) sys.exit(1) if response[0]['accepted'] == False: self.logger.critical("Connection failed: %s" % response[0]['reason']) else: self.logger.info("Connected")
def transmit(self, message): """Send the game state to all clients.""" send_list = [self.socket] readable, writable, in_error = select.select([], send_list, [], 0) for socket in writable: net.send(socket, message, self.username)
def transmit(self, data): """Send data to all clients.""" send_list = self.clients.values() # Select only wriatable sockets. Timeout = 0, instant readable, writable, in_error = select.select([], send_list, [], 0) for socket in writable: net.send(socket, data)
def on_connect(self): """Handle client(s) awaiting connection.""" client, address = self.server_socket.accept() try: username, messages = net.receive(client) except IOError as e: if e.errno == errno.ECONNRESET: self.disconnect_client(client, "Connection lost") else: self.logger.error(e.strerror) return if username in self.clients.keys(): # The username is already taken, refuse connection self.logger.info("Refused connection from %s:%s, " "username '%s' unavailable" % (address[0], address[1], username)) net.send(client, { 'accepted': False, 'reason': 'Username unavailable' }) client.close() return False else: # The username is free, accept the client self.logger.info("Connection from %s:%d, username '%s' accepted" % (address[0], address[1], username)) net.send(client, { 'accepted': True }) self.clients[username] = client # For now, create a vehicle: gameengine.add_entity(Vehicle(username, (400, 300), 120,('bigmotor','smallmotor'))) return True