async def shutdown(self, sig=None): if sig: print(f'[SIGNAL] Got {sig}, closing connections...') await self.game.kill() tasks = [t for t in all_tasks() if t is not current_task()] [task.cancel() for task in tasks] print(f'[SIGNAL] Cancelling tasks...') results = await gather(*tasks, return_exceptions=True) for r in results: if isinstance(r, Exception): print(f'[SIGNAL] Got exception: {r}') print(f'[SIGNAL] Stopping...') loop().stop()
def add(self, session): #广播新用户进入 session.push(b'Login Success') self.broadcast((session.name + 'has entered the room.\n'.encode("utf-8")) self.server.users[session.name]=session Room.add(self, session) def remove(self, session): #广播用户离开 Room.remove(self,session) self.broadcast((session.name +'has left the room.\n').encode("utf-8")) def do_say(self,session,line): #客户端发送消息 self.broadcast((session.name + ':'+line+'\n').encode("utf-8")) def do_look(self, session, line): #查看在线用户 session.push(b'Online Users:\n') for other in self.sessions: session.push((other.name +'\n').encode("utf-8")) if __name__=='__main__': s=ChatServer(PORT) try: print("chat serve run at '0.0.0.0:{0}'.format(PORT)") asyncio.loop() except KeyboardInterrupt: print("chat server exit")
def start(self): start_server = websockets.serve(self.caught, "", self.port) for sig in (SIGTERM, SIGINT): loop().add_signal_handler( sig, lambda sig=sig: create_task(self.shutdown(sig))) loop().run_until_complete(start_server) loop().run_forever()
def _reset(self): self.close() self.loop = loop() asyncio.set_event_loop(self.loop) self.t = 0 allies_info = self._loop_run(self.run_game()) self.allies_client = allies_info[0] self.allies_id = allies_info[1] self.allies_server = allies_info[2] ret_allies = self._ai_preparation(bot_ai=self.allies.ai, player_id=self.allies_id, client=self.allies_client) self.allies_game_data = ret_allies[0] self.allies_game_info = ret_allies[1] self.allies_game_state = ret_allies[2] return self.allies_game_state
#!/usr/bin/python3 from asyncio import new_event_loop as loop from logging import basicConfig, INFO from bot_instance import BotInstance if __name__ == "__main__": basicConfig(level=INFO) client = BotInstance(loop()) try: task = loop().create_task(client.startup()) loop().run_until_complete(task) loop().run_forever() except (KeyboardInterrupt, RuntimeError): print(f"Shutting down - {client.kill()}") except Exception as ex: print(f"Error - {ex}") finally: loop().close()