documented server code

This commit is contained in:
Daniel Fichtinger 2025-07-06 15:23:10 -04:00
parent ecd3e50218
commit a03e9bfb82
2 changed files with 16 additions and 2 deletions

View file

@ -65,9 +65,9 @@ class LiveReloadHandler(SimpleHTTPRequestHandler):
if index_path.is_file():
path = index_path
# check if serving html file
if Path(path).suffix in {".html", ".htm"} and self.script != "":
if path.suffix in {".html", ".htm"} and self.script != "":
try:
logger.debug("Injecting reload script")
logger.debug(f"Injecting reload script: {path}")
# read the html
with open(path, "rb") as f:
content = f.read().decode("utf-8")

View file

@ -5,6 +5,11 @@ from websockets.legacy.server import WebSocketServerProtocol, serve
class WebSocketServer:
"""
Async WebSocket server for live reloading.
Notifies clients when they should reload.
"""
host: str
port: int
clients: set[WebSocketServerProtocol]
@ -19,6 +24,7 @@ class WebSocketServer:
self.thread = None
async def _handler(self, ws: WebSocketServerProtocol):
"""Handle incoming connections by adding to client set."""
self.clients.add(ws)
try:
await ws.wait_closed()
@ -26,19 +32,26 @@ class WebSocketServer:
self.clients.remove(ws)
def start(self):
"""Spin up server."""
def run():
# set up async event loop
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
# start server
ws_server = serve(
ws_handler=self._handler, host=self.host, port=self.port
)
# add server to event loop
self.loop.run_until_complete(ws_server)
self.loop.run_forever()
# spawn async serever in a thread
self.thread = Thread(target=run, daemon=True)
self.thread.start()
async def _broadcast(self, message: str):
"""Broadcast message to all connected clients."""
for ws in self.clients.copy():
try:
await ws.send(message)
@ -46,6 +59,7 @@ class WebSocketServer:
self.clients.discard(ws)
def notify_all(self, message: str = "reload"):
"""Notify all connected clients."""
if self.loop and self.clients:
asyncio.run_coroutine_threadsafe(
coro=self._broadcast(message), loop=self.loop