2

I have websocket opened under a certain port, and when the client web browser closes, I want the websocket to be closed cleanly so that the server program keeps running and accepts a new connection.

Right now, I have client side code as follows:

window.addEventListener('load', function(){
  ws = new WebSocket(url);
  ws.onopen = function(e){...};
  ws.onmessage = function(e){...};
  ws.onerror = function(e){...};
  ws.onclose = function(e){
    alert('Browser Closed');
  };
  window.onbeforeunload = function(e){
    ws.close();
  };
}, false);

When I run the server and open the web browser for connection, it works for the first time. Then, after I close the browser and try to connect again, I get an error because the port is used. This means that, when I closed the browser after the first connection, the websocket ws was not closed cleanly. I am using Google Chrome, and I read that Chrome disables onbeforeunload, so the function bound to that event might not be executed. I can confirm from the alert message that ws.onclose is executed when the browser is closed. How can I make the websocket close cleanly and release the port when the browser is closed? Do I have to do something on the server side as well?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • Just curious: what happens when you close and re-open a WebSocket without closing the page? Does that work as expected, or does it fail in the same way? – apsillers Jul 30 '13 at 14:56
  • I never tried that. How do you do that? – sawa Jul 30 '13 at 14:58
  • What kind of a websocket server you're using? – udidu Jul 30 '13 at 14:58
  • On the client side, I start it with `new WebSocket(url);`. On the server side, I use Ruby and a library called `websocket-eventmachine-server`, which is a modified version of `em-websocket`. – sawa Jul 30 '13 at 15:00
  • Yeah now I see it.. didn't noticed – udidu Jul 30 '13 at 15:00
  • @sawa Just call `ws.close()` in a [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout) function and then (in the same function) create a new WebSocket just like you create your first one. – apsillers Jul 30 '13 at 15:06

0 Answers0