12

I'm using the Spring websocket support. My question is how to set the websocket connection timeout. Now the connection is closed automatically after several minutes. I want the connection never to be closed.

Here is my websocket handler:

public class MyHandler implements WebSocketHandler {
 private Logger logger = LoggerFactory.getLogger(this.getClass());
 class MyTimerTask extends TimerTask {
 private WebSocketSession session;
 public MyTimerTask(WebSocketSession session) {
 this.session = session;
 }
 @Override
 public void run() {
 try {
 String msg = ((int)(Math.random()*50)) + "";
 this.session.sendMessage(new TextMessage(msg.toString()));
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
 @Autowired
 private UserDao userDao;
 @Autowired
 private JdbcDaoImpl jdbcDaoImpl;
 private Timer timer;
 @Override
 public void afterConnectionEstablished(WebSocketSession session)
 throws Exception {
 System.out.println("websocket????");
 timer = new Timer();
 timer.schedule(new MyTimerTask(session), 0, 1000);
 logger.info("logger connection");
 }
 @Override
 public void handleMessage(WebSocketSession session,
 WebSocketMessage<?> message) throws Exception { }
 @Override
 public void handleTransportError(WebSocketSession session,
 Throwable exception) throws Exception { }
 @Override
 public void afterConnectionClosed(WebSocketSession session,
 CloseStatus closeStatus) throws Exception {
 System.out.println("websocket????");
 timer.cancel();
 }
 @Override
 public boolean supportsPartialMessages() {
 return false;
 } 
}

my websocket config:

<websocket:handlers>
 <websocket:mapping path="/myHandler" handler="myHandler"/>
</websocket:handlers>
<bean id="myHandler" class="com.sdp.websocket.MyHandler"/>

and javascript client:

var webserver = 'ws://localhost:8080/authtest/myHandler';
var websocket = new WebSocket(webserver);
websocket.onopen = function (evt) { onOpen(evt) }; 
websocket.onclose = function (evt) { onClose(evt) }; 
websocket.onmessage = function (evt) { onMessage(evt) }; 
websocket.onerror = function (evt) { onError(evt) }; 
function onOpen(evt) { 
 console.log("Connected to WebSocket server."); 
} 
function onClose(evt) { 
 console.log("Disconnected"); 
} 
function onMessage(evt) { 
 console.log('Retrieved data from server: ' + evt.data); 
} 
function onError(evt) { 
 console.log('Error occured: ' + evt.data); 
}
debugger;
function sendMsg(){
 websocket.send("{msg:'hello'}");
}
Bogdan
24.7k3 gold badges74 silver badges64 bronze badges
asked Sep 19, 2014 at 9:07

2 Answers 2

20

The websocket stays opened until either the server or the client decide to close it. However, websockets are affected by two timeouts:

  • HTTP session timeout;
  • proxy connection timeouts;

If all you have between your client and your server is a websocket connection, and you don't interact over HTTP with AJAX or requesting other pages, the HTTP session expires and some servers decide to invalidate it along with the websocket (Tomcat7 had a bug that did just that). Some other servers don't do that because they see there is activity on the websocket. See here for an extended discussion: Need some resolution or clarification for how and when HttpSession last access time gets updated.

The other timeout is with proxies. They see the connection and if there is no activity on the wire for a longer period of time, they just cut it because they think it hanged. To address this, while you don't send actual application data, you need to have a heartbeat or a ping/pong of messages from time to time to let the proxy know that the connection is still OK.

Other issues might also intervene, like a buggy browser support for websocket, how your network is configured, firewall rules, etc.

For available timeout options in Spring see the websocket documentation: Configuring the WebSocket Engine.

answered Sep 20, 2014 at 16:19
Sign up to request clarification or add additional context in comments.

4 Comments

yeah, you are right. It is decided by the session and cookie timeout of Tomcat. I have set the timeout in my web.xml
Check out Spring Session (github.com/spring-projects/spring-session), it keeps the HttpSession alive when a WebSocket is active
Did you change 'session-timeout' in web.xml file of tomcat to fix this issue?
This answer helped me a lot, I implemented a ping pong mechanism and now my app works perfectly fine, so thank you :) :) :)
-1
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
 @Bean
 public ServletServerContainerFactoryBean createWebSocketContainer() {
 var container = new ServletServerContainerFactoryBean();
 container.setMaxSessionIdleTimeout(...);
 return container;
 }
}
answered Jun 3, 2022 at 11:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.