Create a custom WebSocket on binder

Hello,
Trying to connect to a custom WebSocket from a notebook that is running on JupyterLab which is hosted on Binder.

I’m running this code from a notebook cell

def start_websocket_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    start_server = websockets.serve(handler, "127.0.0.1", 36277)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

websocket_thread = threading.Thread(target=start_websocket_server)
websocket_thread.start()

Now, I want to connect to this socket using JS

let socket = new WebSocket(`ws://127.0.0.1:36277`);
 
socket.addEventListener('open', function (event) {
    socket.send('Connection Established');
});

socket.addEventListener('message', function (event) {
    console.log(event.data);
});

It’s working locally on Jupytet-lab but it doesn’t work on Binder hub (let’s say my binder url is : “https://hub.binder.example.com”).

To run it on Binder I changed the socket initialization to :

start_server = websockets.serve(handler, "0.0.0.0", 36277)

and to connect it:
new WebSocket(wss://hub.binder.example.com:36277);

I think the issue might be with my binder configuration and the IP address I’m trying to connect to.

Any suggestions here?

On MyBinder.org, for example, you only get one external-facing port, and there is no working around it. On your own… well, the sky’s the limit.

jupyter-server-proxy provides a few ways to wrap local ports from other processes in a way that reuses the existing 8888-equivalent port required to make the Jupyter client/server exchange work. This works well on binder.

2 Likes