feat: add ability to close connection

This commit is contained in:
2021-07-05 12:44:29 -04:00
parent f8166435d1
commit f67bfcfb24
2 changed files with 21 additions and 2 deletions

View File

@@ -65,6 +65,7 @@ class Game:
self.next_piece = PieceGenerator.get_piece((620, 160)) # (360, 100) self.next_piece = PieceGenerator.get_piece((620, 160)) # (360, 100)
if self.stack and self.current_piece.collide(self.stack): # TODO game over redo if self.stack and self.current_piece.collide(self.stack): # TODO game over redo
pygame.quit() pygame.quit()
MultiplayerService.quit()
sys.exit() sys.exit()
if self.stack: if self.stack:
@@ -73,6 +74,7 @@ class Game:
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: if event.type == pygame.QUIT:
pygame.quit() pygame.quit()
MultiplayerService.quit()
sys.exit() sys.exit()
def draw(self) -> None: def draw(self) -> None:

View File

@@ -7,22 +7,39 @@ class MultiplayerService():
@classmethod @classmethod
def init(cls): def init(cls):
thread = Thread(target=asyncio.get_event_loop().run_until_complete, args=(_NetworkConnectionService.init(),)) thread = Thread(target=asyncio.get_event_loop().run_until_complete,\
args=(_NetworkConnectionService.init(),))
thread.start() thread.start()
@classmethod
def quit(cls):
_NetworkConnectionService.close_connection()
class _NetworkConnectionService(): class _NetworkConnectionService():
_websocket = None _websocket = None
_URI = "ws://localhost:5001" _URI = "ws://webapi.tetri5.com"
_is_closed = False
@classmethod @classmethod
async def init(cls): async def init(cls):
await cls._connect_to_server() await cls._connect_to_server()
await cls._run_network_loop()
@classmethod
def close_connection(cls):
cls._is_closed = True
@classmethod
async def _run_network_loop(cls):
while True: while True:
await asyncio.sleep(16e-3) await asyncio.sleep(16e-3)
await cls._websocket.send("ping") await cls._websocket.send("ping")
print(await cls._websocket.recv()) print(await cls._websocket.recv())
if cls._is_closed:
await cls._websocket.close()
break
@classmethod @classmethod
async def _connect_to_server(cls): async def _connect_to_server(cls):
print("Connecting to server...") print("Connecting to server...")