How do you quickly close a nonresponsive websocket in Java Spring Tomcat? How do you quickly close a nonresponsive websocket in Java Spring Tomcat? spring spring

How do you quickly close a nonresponsive websocket in Java Spring Tomcat?


ServletServerContainerFactoryBean simply configures the underlying JSR-356 WebSocketContainer through Spring configuration on startup. If you peek inside you'll see it's trivial.

From what I can see in Tomcat code about the handling of maxSessionIdleTimeout, the WsWebSocketContainer#backgroundProcess() method runs every 10 seconds by default to see if there are expired sessions.

I suspect also the pings you're sending from the server are making the session appear active, hence not helping with regards to the idle session timeout configuration.

As to why Tomcat doesn't realize the client is disconnected sooner, I can't really say. In my experience if a client closes a WebSocket connection or if I kill the browser it's detected immediately. In any case that's more to do with Tomcat not Spring.


The approach I eventually took was to implement an application-layer ping-pong protocol.

  • The server sends a ping message with period p to the client.
  • The client responds to each ping message with a pong message.
  • If the server sends more than n ping messages without receiving a pong response, it generates a timeout event.
  • The client can also generate a timeout event if it does not receive a ping message in n*p time.

There should be a much simpler way of implementing this using timeouts in the underlying TCP connection.