Persist Sockets over page refresh and page changes

2019-07-16 14:32发布

问题:

I have my NodeJS and Socket.IO server running perfectly, however I notice that a socket disconnect and reconnect occurs every time I refresh the browswer page or navigate to a different page.

How do I make it so sockets persist between pages?


Thanks, I thought of that but wanted to avoid it as it's quite a big change for the system I'm making and would be a fair bit of work.

The only thing the socket connects/disconnects will effect is a "users logged in" counter. But I think I can get around that with a setTimeout on the Node server, so if a socket disconnects and reconnects within 2 seconds, the counter won't change. Is that the best work around in terms of this counter?

回答1:

You can't really do that: network connections do not survive page navigation or refreshes. If you really really care you'll basically need to build a single page application.



回答2:

you could use AJAX to navigate between the pages, to avoid the page refresh/socket disconnect