How to close websocket and release a port

2k Views Asked by At

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?

0

There are 0 best solutions below