feat: improve websocket connection performance

This commit is contained in:
2021-07-05 12:04:00 -04:00
parent 4be068dae1
commit f8166435d1
2 changed files with 19 additions and 30 deletions

View File

@@ -2,38 +2,31 @@ 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
class MultiplayerService():
_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 = Thread(target=asyncio.get_event_loop().run_until_complete, args=(_NetworkConnectionService.init(),))
thread.start()
class _NetworkConnectionService():
_websocket = None
_URI = "ws://localhost:5001"
@classmethod
def update(cls):
cls._thread_pool = list(filter(lambda t: t.is_alive(), cls._thread_pool))
async def init(cls):
await cls._connect_to_server()
while True:
await asyncio.sleep(16e-3)
await cls._websocket.send("ping")
print(await cls._websocket.recv())
@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
cls._websocket = await websockets.connect(cls._URI, ping_interval=None)
# ping_interval=None is important, otherwise the server will disconnect us
# https://stackoverflow.com/a/58993145/11512104
print("Connected to server...")