32 lines
970 B
Python
32 lines
970 B
Python
import asyncio
|
|
import websockets
|
|
from threading import Thread
|
|
|
|
class MultiplayerService():
|
|
_thread = None
|
|
|
|
@classmethod
|
|
def init(cls):
|
|
thread = Thread(target=asyncio.get_event_loop().run_until_complete, args=(_NetworkConnectionService.init(),))
|
|
thread.start()
|
|
|
|
class _NetworkConnectionService():
|
|
_websocket = None
|
|
_URI = "ws://localhost:5001"
|
|
|
|
@classmethod
|
|
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, ping_interval=None)
|
|
# ping_interval=None is important, otherwise the server will disconnect us
|
|
# https://stackoverflow.com/a/58993145/11512104
|
|
print("Connected to server...") |