Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring websocket timeout settings

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'}");
}
like image 238
user3135996 Avatar asked Sep 19 '14 09:09

user3135996


People also ask

Can a WebSocket timeout?

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.

How long WebSockets stay open?

However, the connection between a client and your WebSocket app closes when no traffic is sent between them for 60 seconds.

What is Ping and Pong in WebSocket?

Pings and Pongs: The Heartbeat of WebSocketsA ping or pong is just a regular frame, but it's a control frame. Pings have an opcode of 0x9 , and pongs have an opcode of 0xA . When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125).

What is enableStompBrokerRelay?

The enableStompBrokerRelay method returns a convenient Registration instance that exposes a fluent API. You can use this fluent API to configure your Broker relay: registry.


1 Answers

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.

like image 80
Bogdan Avatar answered Oct 08 '22 00:10

Bogdan