Search code examples
javascriptpythonwebsockettornado

Is it possible to send a Websocket connection to a client?


folks!

I have the following scenario:

  • I'm running a Tornado server with a WebSocketHandler that handles open, on_message and on_close events on a websocket:

     class WebSocketHandler(tornado.websocket.WebSocketHandler):
         def open(self):
             (...)
         def on_message(self, message):
             (...)
         def on_close(self):
             (...)
    
  • I have a view where the client opens a new WebSocket and sets the "onmessage" event handler:

     window.onload = function() {
         ws = new WebSocket("ws://192.168.0.51:8080/websocket");    
         ws.onmessage = function(e) {
             console.log(e.data);
         };
     }
    
  • I would like to change this example a little bit to "reuse" a websocket connection if the user, let's say, opens a new tab in his browser but he has already an opened websocket at the server side.

    I'm intending to do this by sending a user unique id when making the first request to the server and checking the response, before opening a socket.

    Question is: If the Tornado server detects that the user already has an opened connection (websocket), is it possible to send to that user(client) a reference to that connection in order to enable the client side code to use it instead of creating a new one?

Thanks in advance!


Solution

  • In principle, this can be achieved by opening the WebSocket connection from a shared background Web worker.

    Opening WebSocket connections from Web workers is not supported (yet) by all browsers. I know it works with dedicated Web workers on Chrome and IE11, and it does not work with Firefox.

    I don't know which browsers support opening WebSocket connections from shared Web workers.