def keepAlive(self): global KeepAliveTimeWait keepAliveTimer = time.time() - random.randint( 0, int(KeepAliveTimeWait / 2)) while self.isOnline(): if time.time() - keepAliveTimer >= keepAliveInterval: try: self.keepAliveResponded = False self.log('Keep alive pinging...') self.send_keepAlive('ping') except socket.error as err: self.log( 'Failed to send keep alive data, error = {}, stopping client now' .format(err.args)) self.stop() else: keepAliveSentTime = time.time() while self.isOnline( ) and self.keepAliveResponded == False and time.time( ) - keepAliveSentTime <= KeepAliveTimeWait: utils.sleep() if not self.isOnline(): break if self.keepAliveResponded: self.log('Keep alive responded, ping = {}ms'.format( round((time.time() - keepAliveSentTime) * 1000, 1))) else: self.log('No respond for keep alive, stop the client') self.stop() keepAliveTimer = time.time() utils.sleep()
def run(self): self.sock = socket.socket() try: self.sock.bind(self.server_addr) except socket.error: self.log('Fail to bind ' + str(self.server_addr)) return False self.sock.listen(5) self.online = True self.log('Server Started') while self.isOnline(): conn, addr = self.sock.accept() self.log( 'Client {0} connected, receiving initializing data'.format( utils.addressToString(addr))) try: js = json.loads(self.recieveData(conn)) # 接受客户端信息的数据包 self.log('Initializing data =' + str(js)) if js['action'] == 'login': info = lib.ChatClientInfo(js['name'], js['password']) flag = False for client in self.clients: if client.info == info: self.send_result('login success', conn) flag = True self.log('Starting client "' + client.info.name + '"') client.tryStart(conn, addr) break if flag == False: self.send_result('login fail', conn) else: self.log('Action not matches, ignore') except (ValueError, TypeError, KeyError) as err: self.log('Fail to read received initializing json data: ' + str(err)) except socket.error: self.log('Fail to respond the client') utils.sleep() return True
def run(self): self.sock = socket.socket() try: self.sock.bind(self.server_addr) except socket.error: self.log('Fail to bind ' + str(self.server_addr)) return False self.sock.listen(5) self.online = True self.log('Server Started') self.start_console_thread() try: while self.isOnline(): conn, addr = self.sock.accept() self.handle_client_connection(conn, addr) self.log( 'Client {0} connected, receiving initializing data'.format( utils.addressToString(addr))) utils.sleep() except: if self.isOnline(): raise return True