Files
tetri5/tetris/online.py
2021-07-02 20:51:10 -04:00

40 lines
1.2 KiB
Python

import asyncio
import websockets
from threading import Thread
class OnlineService():
_URI = "ws://localhost:5001" # TODO remove hardcoded URI and add to config file
_TIMEOUT = 5 / 1000 # Timeout in seconds
_websocket = None
_thread = None
@classmethod
def init(cls):
thread = Thread(target=asyncio.get_event_loop().run_until_complete, args=(cls._connect_to_server(),))
cls._thread_pool.append(thread)
thread.start()
@classmethod
def update(cls):
cls._thread_pool = list(filter(lambda t: t.is_alive(), cls._thread_pool))
@classmethod
async def _connect_to_server(cls):
print("Connecting to server...")
cls._websocket = await websockets.connect(cls._URI)
print("Connected to server...")
@classmethod
def ping_server(cls):
thread = Thread(target=asyncio.get_event_loop().run_until_complete, args=(cls._ping_server(),))
cls._thread_pool.append(thread)
thread.start()
@classmethod
async def _ping_server(cls):
if cls._websocket is not None:
await cls._websocket.send("ping")
# IDEAS
# Create running ONE thread that handles requests and reponses to the server in one running loop