def listening(self): """ loop in which the client waits for the servers bewegeString and answers with his calculated destination after we get 'Ende' the ssl connection will be closed """ while True: try: bewegeString = read(self.connection) if self.worldSize == None: write(self.connection, 'Weltgroesse?') self.worldSize = read(self.connection) print 'world size:', self.worldSize print 'bewegeString=' + bewegeString #string which is given by the server if 'Ende' in bewegeString: break #sending our calculated destination destination = str(self.beast.bewege(bewegeString)) if len(destination) > 0 and destination != 'None': print 'sent=' + destination write(self.connection, destination) except Exception as e: print time.asctime(), e, ': lost connection to Server' break self.connection.close()
def registration(self): """ default activity with requests and responses between client and server after sending 'Anmeldung!' and receiving an char the client is registered and the listening-loop will be started """ if not self.connectToServer(): return request = 'Spielbeginn?' print 'request:', request write(self.connection, request) response = read(self.connection) print 'cur time:', time.asctime() print 'response:', response write(self.connection, 'Anmeldung moeglich?') if read(self.connection) == 'Ja': print 'Anmeldung moeglich? Ja' write(self.connection, 'Anmeldung!') response = read(self.connection) if response in string.ascii_letters and len(response) == 1: print 'Assigned Beast name:', response print 'Waiting for bewege() requests...' else: print 'Anmeldung gescheitert' return else: print 'Anmeldung gescheitert' return self.listening()
def registerBeast(self): """ called by registration() register the client in current game """ write(self.connection, "Anmeldung!") beastName = read(self.connection) return beastName
def getGameStartTime(self): """ sends ask for the start time of next game to GUI """ if 10008 in self.hostPort: write(self.connection, "startdelay?") else: write(self.connection, "Spielbeginn?") self.emit(QtCore.SIGNAL('sendStartTime(QString)'),read(self.connection))
def listening(self): """ loop in which the client waits for the servers bewegeString bewegeString is split to particular arguments which will be sent to GUI after we get 'Ende' the ssl connection will be closed """ while self.running: try: self.bewegeString = read(self.connection) surrounding = self.bewegeString.split(';')[1] energy = self.bewegeString.split(';')[0] worldBeforeTenRounds=self.bewegeString.split(';')[2] if self.deadBeast and worldBeforeTenRounds!='': time.sleep(0.2) if self.worldSize == None: write(self.connection, 'Weltgroesse?') self.worldSize = read(self.connection) if 'Ende' in self.bewegeString: if self.connectedToServer: self.leaveServer() if self.bewegeString.startswith(';;'): self.deadBeast = True if 'Ende' in self.bewegeString: semiCounter=0 counter=0 while semiCounter<2: if self.bewegeString[counter]==';': semiCounter+=1 counter+=1 strLastTenRounds=self.bewegeString[counter:] self.emit(QtCore.SIGNAL("notify(QString,QString,QString)"), surrounding, energy, strLastTenRounds) break self.emit(QtCore.SIGNAL("notify(QString,QString,QString)"), surrounding, energy, worldBeforeTenRounds) except Exception as e: print time.asctime(), e, ': lost connection to Server' self.leaveServer()
def isRegisterAllowed(self): """ called by registration() checks if server provides an open game to register in """ write(self.connection, "Anmeldung moeglich?") response = read(self.connection) if response == 'Ja': return True return False
def bewege(self, paramString): """ forwards the paramString to the client @param paramString string from server @return destination by the client's beast calculated destination """ try: if self.socket is None: return '' write(self.socket, paramString) params = paramString.split(';', 2) energy = params[0] environment = params[1] try: intEnergy = int(energy) except ValueError: intEnergy = 0 if len(energy) > 0 and intEnergy > 0 and environment != 'Ende': timeoutTime = time.time() + 5 # 5 s timeout while time.time() < timeoutTime: time.sleep(0.1) inputReady, outputReady, exceptionReady = select.select([self.socket], [], [], 0) for sendingClient in inputReady: answer = read(sendingClient) if answer == '?': return answer try: if int(answer) in range(25): return answer except ValueError: # parsing to int pass if len(answer) > 0: write(self.socket, self.server.processClientCommunication(socket, answer)) return '' # if we haven't received a move after 5 s, return empty string except socket.error as e: self.log.warning(str(e) + ',socket.error: closing socket') self.socket.close() self.socket = None except AttributeError as e: # catch AttributeError: 'NoneType' object has no attribute 'write' self.log.warning(str(e) + ',AttributeError: closing socket') self.socket.close() self.socket = None
def run(self): self.running=True try: self.log.info('Starting server on port ' + str(Config.__getPort__()) + '...') self.bindsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.bindsocket.bind(('', Config.__getPort__())) self.bindsocket.listen(5) self.bindsocket.settimeout(0.1) while self.running: # initialize self.closeConnections() self.clientMap = {} self.clientIpCountMap = {} while self.running and not self.game.gameFinished: try: # prevent exception if no client wants to connect newsocket, fromaddr = self.bindsocket.accept() newsocket.settimeout(0.1) if (Config.__getSSL__()): client = ssl.wrap_socket(newsocket, server_side=True, certfile="ssl/server.crt", keyfile="ssl/server.key", ssl_version=ssl.PROTOCOL_SSLv3) else: client = newsocket self.clientMap[client] = fromaddr, None self.log.info('client ' + str(self.clientMap[client]) + ' has connected') except KeyboardInterrupt: self.log.info('\nCtrl-C was pressed, stopping server...') self.bindsocket.close() self.log.info('Server stopped.') sys.exit() except socket.timeout: pass except socket.error as e: # Spits out tons of exceptions self.log.info(str(e.errno) + str(e)) inputReady, outputReady, exceptionReady = select.select(self.clientMap.keys(), [], [], 0) for client in inputReady: # go through all clients which sent a request clientip = None #Overwritten by local variables?? TODO: check! -> see line 86 #try: request = read(client) #except Exception as e: # print e response = self.processClientCommunication(client, request) self.log.info('current clients: ' + str(self.clientMap)) self.log.info('current IP-Connections: ' + str(self.clientIpCountMap)) try: # prevent exceptions if client has disconnected write(client, response) except: self.log.info('client ' + str(self.clientMap[client]) + ' has gone') self.clientMap.pop(client) self.decreaseClientIpConnections(clientip) for client in exceptionReady and self.running: self.log.info('assumed shutdown() -> exception occurred with client: ', str(self.clientMap[client])) if self.clientMap.has_key(client): client.shutdown(socket.RDWR) client.close() self.clientMap.pop(client) self.decreaseClientIpConnections(clientip) time.sleep(0.01) finally: self.closeConnections() self.bindsocket.close()