Keep Connection with Socket.io

2019-08-07 15:15发布

问题:

I'm trying to connect at asterisk websocket, using socket.io-client

socket = io.connect(url ,{
    transports: ['websocket'],
    secure: true,
    'force new connection' : false,
    'reconnect' : true,
});

It works, but everytime I change or refresh page, websocket connection disconnect and reconnect (obviusly). My app is not "one-page-app".

There is a way for keep connection alive?

回答1:

There is a way for keep connection alive?

No. Not if you allow the page to change in the browser.

When the browser changes pages, it will close all resources associated with the old page (including webSockets) and then it will initialize and open the new page. You cannot change that.

The only way to keep a webSocket open is to put it in a window that does not change. That would entail either converting to a single page app (that doesn't change pages) or putting the webSocket in a frame or window that doesn't change. You could have the user install a browser extension (which can maintain persistent connections), but I assume that isn't what you're asking about.

Otherwise, you have to just manage things on your server to handle the fact that a page change within your site will close the old webSocket and open a new one.