Bokeh 2.0 websockets

In Bokeh 1.4 we implemented an onclose response on the Bokeh websocket. We used something like this to get to get a handle to a Bokeh websocket:

var webSocket = new WebSocket("ws://"+ window.location.href.split("//")[1] +"/ws?bokeh-protocol-version=1.1&bokeh-session-id="+sessionID, "bokeh");

webSocket.onclose = function() {
 $(".lostconnection").show();
}

This however does not work in Bokeh 2.0 anymore. We now get an error:
raise ProtocolError(“Subprotocol header is not ‘bokeh’”)

I saw in the documentation of Bokeh 2.0 that bokeh-protocol-version is no longer used and that Bokeh now uses a token system, but I am not sure how to use the new system to get a handle to the websocket and trigger the onclose again.

How can we achieve this?

This is how BokehJS itself create a WebSocket: bokeh/connection.ts at be6326f1293f94a61110c8487af19458a2ce1667 · bokeh/bokeh · GitHub

@p-himik, thanks for your pointer, looks helpful, we will further investigate this. The next question is now how to create a websocket that does not trigger a new connection (otherwise initialisation code is triggered twice). We found that serverconnection has an attribute _token which perhaps could be used to connect to an existing connection. But if that would work, how to then get access to the token in our JS layer. Inserting it in the html would be a security risk?

I don’t understand, especially the part about “connecting to an existing connection”.
Let’s start from the very beginning. What is the problem that you’re trying to solve? Is it just to show that .lostconnection element when the connection is lost?

Indeed, that is the end goal. To indicate the user somehow the connection was lost.

I meant connecting to an existing session. We now managed by using the ._token information into creating the new websocket and we just found using an existing token does not create a new session on the server side, so no double initialization.

We now managed doing the following:
Python:
curdoc().template_variables["token"] = curdoc().session_context._token

html:
<div id="token" style="display: none;">{{ token }}</div>

js:

That would still result in a double amount of data being sent from the server to all clients.
Right now there’s no good way of notifying about the loss of a connection. To avoid having to open another connection, I would probably intercept all Bokeh log messages and look out for the messages that start with “Lost websocket”.