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:
Is this something that the websocket protocol requires and in this case the chrome browser is closing my connection?
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?
Is there another problem??
Thanks
UPDATE: even if I send 1 message/second still the connection is closed
The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.
To keep the session active, use a timer to send data periodically. The WebSocket protocol defines a ping/pong mechanism, but the WebSocket API in HTML5 does not expose direct access to that mechanism, though web browsers may handle it internally in their WebSocket implementation.
A WebSocket times out if no read or write activity occurs and no Ping messages are received within the configured timeout period. The container enforces a 30-second timeout period as the default. If the timeout period is set to -1 , no timeout period is set for the connection.
WebSocket uses HTTP as the initial transport mechanism, but keeps the TCP connection alive after the HTTP response is received so that it can be used for sending messages between client and server.
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); }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With