Compare commits

..

3 Commits

Author SHA1 Message Date
Sebastian Lohff 2a0648bcd5 server: send leave to client if they want to leave
When we restart the signal server, the client might reconnect and still
think it has state (i.e. is on a frequency). We should fix this in the
client, but meanwhile we can just send out a leave to a client if they
request to leave a frequency, even if they are not currently on a
frequency.
2025-05-11 01:35:14 +02:00
Sebastian Lohff 024160c169 server: migrate to logging
Timestamps for every print, will make debugging latency issues easier,
maybe.
2025-05-11 01:35:09 +02:00
Sebastian Lohff 615840ac9f server: use websocket's own broadcast method()
I hope this will reduce latency. Initial tests looked a bit better but
not great.
2025-05-11 00:15:31 +02:00
1 changed files with 27 additions and 26 deletions

View File

@ -1,18 +1,20 @@
import asyncio
import datetime
import json
import logging
import re
from websockets.asyncio.connection import broadcast
from websockets.asyncio.server import serve
__VERSION__ = "0.0.1"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(name)s %(levelname)s %(message)s"
format="%(asctime)s %(levelname)s %(message)s"
)
LOG = logging.getLogger()
class Client:
freqs = {}
@ -23,7 +25,7 @@ class Client:
self.curr_freq = None
async def handle(self):
print(f" >>> New client {self.client} connected")
LOG.info(">>> New client %s connected", self.client)
exc = None
try:
await self._handle_client()
@ -31,7 +33,7 @@ class Client:
exc = e
finally:
# FIXME: basically handle disconnect / leave from room
print(f" <<< Client {self.client} id {self.id} disconnected: {exc}")
LOG.info("<<< Client %s id %s disconnected: %s", self.client, self.id, exc)
if self.curr_freq:
await self._leave_room()
@ -49,18 +51,19 @@ class Client:
async def _handle_client(self):
await self._send(type="hello", name="LobbySrv 3000", version=__VERSION__)
async for data in self.websocket:
print(f" <-- client {self.client} sent {repr(data)}")
try:
data = json.loads(data)
except json.JSONDecodeError:
self._send_error("Could not decode message, invalid json")
LOG.error("client %s sent broken data %s", self.client, repr(data))
continue
if not isinstance(data, dict) or "cmd" not in data:
await self._send_error("Invalid format in json")
LOG.error("client %s sent broken data (no cmd key in data) %s", self.client, repr(data))
continue
print(f"{datetime.datetime.now()} {self.client} wrote:", data)
LOG.info("client %s wrote: %s", self.client, data)
match data["cmd"]:
case "quit":
@ -124,7 +127,7 @@ class Client:
self.curr_freq = freq
self.freqs[freq].append(self)
# FIXME: do we need locking here?
print("FREQ", self.curr_freq, freq, self.freqs)
LOG.debug("FREQ %s %s %s", self.curr_freq, freq, self.freqs)
await self._send(type="join", freq=self.curr_freq, self_id=self.id,
other_players=[c.id for c in self._others(freq)])
await self._send_to_group(self._others(freq), type="player-joined", player=self.id)
@ -142,19 +145,18 @@ class Client:
type="morse-state", state=data["state"], from_player=self.id)
async def _leave_room(self):
if not self.curr_freq:
self._send_error("You are not on a frequency")
return
await self._send_to_group(self._others(self.curr_freq),
type="player-left", player=self.id)
try:
self.freqs[self.curr_freq].remove(self)
except ValueError:
print(f"Warning: Player {self.id} was not in freq {self.curr_freq}")
if not self.freqs[self.curr_freq]:
del self.freqs[self.curr_freq]
self.curr_freq = None
if self.curr_freq:
await self._send_to_group(self._others(self.curr_freq),
type="player-left", player=self.id)
try:
self.freqs[self.curr_freq].remove(self)
except ValueError:
LOG.warning("Player %s was not in freq %s", self.id, self.curr_freq)
if not self.freqs[self.curr_freq]:
del self.freqs[self.curr_freq]
self.curr_freq = None
else:
LOG.warning("Client %s is not on a frequency, sending a 'leave' nontheless", self.client)
try:
await self._send(type="leave")
@ -166,18 +168,17 @@ class Client:
async def _send(self, ignore_exceptions=False, **kwargs):
data = json.dumps(kwargs).encode()
print(f" --> sending out to {self.client}: {data}")
LOG.debug("--> sending out to %s: %s", self.client, data)
try:
await self.websocket.send(json.dumps(kwargs).encode() + b"\n")
except Exception as e:
print(f"Error sending data to {self.client}: {e}")
LOG.error("Error sending data to %s: %s", self.client, e)
if not ignore_exceptions:
raise
async def _send_to_group(self, group, **kwargs):
async with asyncio.TaskGroup() as tg:
for member in group:
tg.create_task(member._send(ignore_exceptions=True, **kwargs))
LOG.info("broadcast() to %s clients: %s", len(group), kwargs)
broadcast([c.websocket for c in group], json.dumps(kwargs).encode() + b"\n")
async def _send_error(self, msg: str):
await self._send(type="error", message=msg)
@ -200,5 +201,5 @@ async def main():
if __name__ == "__main__":
print("Starting server")
LOG.info("Starting server")
asyncio.run(main())