use sanic to allow serving web page and websocket from the same port

This commit is contained in:
liamcottle 2024-04-29 14:51:47 +12:00
commit f77f4e74d4
2 changed files with 15 additions and 5 deletions

View file

@ -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;

18
web.py
View file

@ -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)