-
Notifications
You must be signed in to change notification settings - Fork 230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用socket.io遇到的一些坑 #6
Comments
刚好碰到这个socket事件重复监听的问题,谢谢。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
一、給指定的用户发送消息
为了给指定的用户发送消息,我们需要建立一张hash表,键为用户的id,值为该用户连接时生成的socketid。并把这张表以json的格式存储在服务端的users.json文件里。每次登陆的时候就把用户的id和socketid存储到服务器端。具体怎么实现可以参考问题二里的服务端代码。
二、用户手动刷新或者重新打开浏览器,原来的socketid会失效
如果用户手动刷新或者重新打开浏览器(都可视为刷新),那么服务器端保存的该用户对应的socketid会失效,因为刷新会导致connection,会生成新的socketid。这样导致的问题就是服务端无法继续给指定的用户推送消息了(socketid失效)。
解决方案如下:
客户端:每次连接服务端的时候就emit用户的id。当然得先判断下用户是否已经登陆了,没有登陆的话,自然无法获取用户的id,无法emit,这种情况就只能等用户登陆了再emit用户的id。
客户端需要在两个地方emit用户的id:
(1)登录时(emit用户id)
(2)连接时(需判断是否已经登陆)
服务端:同时监听login事件和update事件
socket.js:
fs-async.js:
users.json:
三、socket事件重复监听的问题
在单页应用里,使用socket.on监听事件前一定要先移除原来的事件。不然会导致生成重复的监听器。
The text was updated successfully, but these errors were encountered: