websocket closing connection automatically

Doua Beri picture Doua Beri · Jan 29, 2012 · Viewed 127.8k times · Source

I'm building an application in java that has an embedded websocket server based on jetty. The client is the default websocket implementation in google chrome. Everything is working ok, only if there is no transfer between server and client after a certain time the connection is closed. I'm not sure who's closing the connection: the jetty server or the chrome browser.

The solution to this I think is to send a message every x seconds, but I'm opened to better solutions.

SO... my questions are:

  1. Is this something that the websocket protocol requires and in this case the chrome browser is closing my connection?

  2. Is this something that is more jetty related and has more or less to do with the websocket protocol? In this case how do I disable this in jetty?

  3. Is there another problem??

Thanks

UPDATE: even if I send 1 message/second still the connection is closed

Answer

Ant Kutschera picture Ant Kutschera · Mar 8, 2015

In answer to your third question: your client wants to be able to cope with temporary network problems anyway, e.g. let's say the user closes their laptop between meetings which hibernates it, or the network simply goes down temporarily.

The solution is to listen to onclose events on the web socket client and when they occur, set a client side timeout to re-open the connection, say in a second:

function setupWebSocket(){
    this.ws = new WebSocket('wss://host:port/path');
    this.ws.onerror = ...;
    this.ws.onopen = ...;
    this.ws.onmessage = ...;
    this.ws.onclose = function(){
        setTimeout(setupWebSocket, 1000);
    };
}