Angular single page app and socketio multiple sockets

≡放荡痞女 提交于 2019-12-23 05:25:40

问题


I have yet to find a solution or any information on this topic. Basically I am developing a chat app with flask, socketio, and angularjs. I created a single page app with angularjs so when I click for example a register button this page comes into view even though it is not actually routing to a new page. The problem is when I click the register button or switch views another socket connection gets created. So when I go back to the chat app view to send a message it sends 3 messages because 3 sockets were created. One initially, one when I went to register view and the third socket connection was created when I went back to chat app view. So I have a few questions about this behavior:

In a non-SPA would this behavior still happen?

Does a socket get disconnected when switching pages in a non-SPA?

With my issue I can see that changing views in a SPA creates another socket but it does not delete a socket. How do I avoid having multiple socket connections so I do not send multiple messages/events for a single sent message event?

Thanks a lot guys.


回答1:


In a non-SPA would this behavior still happen? Does a socket get disconnected when switching pages in a non-SPA?

In a non-SPA, when you move from one page to another, the browser deletes any connections the old page still has open. Each page runs in a completely separate context.

In a SPA, you should move your socket creation code to a top-level module, something that runs only when the app initializes, but not when you switch from one page to another. So you will be using a single socketio instance through the life of the application.




回答2:


The best practices as to me would be to use Shared Worker as a thread for socket connection. It's guaranteed that there will be only one instance of Shared Worker for all the tabs of your applications thus you'll definitely have only one socket connection.



来源:https://stackoverflow.com/questions/36214312/angular-single-page-app-and-socketio-multiple-sockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!