From f77f4e74d4656ebe02c86ae34e0f284b9fed1d7a Mon Sep 17 00:00:00 2001 From: liamcottle Date: Mon, 29 Apr 2024 14:51:47 +1200 Subject: [PATCH] use sanic to allow serving web page and websocket from the same port --- index.html | 2 +- web.py | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/index.html b/index.html index 403b6cd..d07ff07 100644 --- a/index.html +++ b/index.html @@ -159,7 +159,7 @@ connectWebsocket: function() { // connect to websocket - this.ws = new WebSocket("ws://localhost:8000"); + this.ws = new WebSocket(location.origin.replace(/^http/, 'ws') + "/ws"); this.ws.addEventListener('open', () => { this.isWebsocketConnected = true; diff --git a/web.py b/web.py index 8a1d186..6ddb35d 100644 --- a/web.py +++ b/web.py @@ -8,6 +8,11 @@ import asyncio import websockets import base64 +from sanic import Sanic, Request, Websocket, file + +# create sanic app +app = Sanic("ReticulumWebChat") + # init reticulum reticulum = RNS.Reticulum(None) @@ -27,16 +32,21 @@ websocket_clients = [] async def main(): + # run sanic app + app.run() + # set a callback for when an lxmf message is received message_router.register_delivery_callback(lxmf_delivery) - # start websocket server - async with websockets.serve(on_websocket_client_connected, "", 8000): - await asyncio.Future() # run forever + +@app.get("/") +async def hello_world(request): + return await file("index.html") # handle websocket messages -async def on_websocket_client_connected(client): +@app.websocket("/ws") +async def on_websocket_client_connected(request: Request, client: Websocket): # add client to connected clients list websocket_clients.append(client)