Panel serve: is it possible to open a WebSocket to the running app?

I have been experimenting with WebSockets. (I am new to this,
but have some stand alone examples worked out).

My question: can I add a WebSocket connection to a panel app
served wit panel serve and have it exercise an async function?

I have not been able to figure it out!

I got a little further: notebook cell code:

%%javascript

var ws = new WebSocket("ws://localhost:8678/websocket");
ws.onopen = function() {
   alert("Hello, world");
};
ws.onmessage = function (evt) {
    let dat = JSON.parse(event.data);
    console.log(dat);
    alert(evt.data);
};
ws.onclose = function (evt) {
    alert( "ByBye!!!");
}

python script producer.py

# WS server that sends messages at random intervals

import asyncio
import random
import numpy as np
import json
import websockets

async def produce(websocket, path):
    l =  [1.1,2.2,'troglodyte', -3.3,4.4,5.,6.,7.,8.8]

    while True:
        n = random.randint(1,len(l));
        await websocket.send( json.dumps(l[0:n], ensure_ascii=False) )
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve( produce, "127.0.0.1", 8678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

but I need to run the producer.py code before executing the notebook cell. :frowning:
No idea yet how to close/reopen the connection, and how to make the startup order abitrary…

Figured out enough of the pieces, though very simplistic:
I had never played with this type of code before:


has a number of versions:
websocket python <-> python, python <-> javascript, and python <-> javascript in a notebook
3 Likes