Question

I'm using Play Framework 2.2.1 on to handle the WebSocket connections.

In general, the following onClose function is called when the connection is either closed by the client in purpose (by calling close function) or it gets closed by unwanted events such as if the client gets crashed.

socketIn.onClose(new F.Callback0() {
                    public void invoke() {
                             // Send a Quit message
                        }
                       });

The problem here is, sometimes, in case of unwanted events, the onClose callback is not called. From the server point of view, the client looks like it is still connected. What is the best way to handle this problem? Should I ping the client like every second to see he is online, or maybe a ping from client to server?

Was it helpful?

Solution

Unfortunately, there's no easy solution. Here's a issue about it on Play's github. Specifically, it's not possible for Play to infer that the connection is lost by itself.

Until Play supports read/idle timeouts, you can implement them yourself. Our browser extension keeps a persistent websocket connection, and we run application-level pings every x seconds. Both the client and server can initiate a disconnect if the line has been quiet for too long.

I'm not as familiar with the Java websocket API, but abstractly, you just want to keep a record of the last communication time on the server, and have a thread / actor / scheduled task clean up old connections. Then, to keep the connection alive, run pings down the socket. We initiate pings on the client (but on the server works as well), and if the server does not pong within 2 seconds, the client disconnects and reconnects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top