Socket.io - Implementing a user-socket association map for private messaging

前端 未结 4 1947
既然无缘
既然无缘 2021-02-09 23:23

I\'m trying to create a private messaging system using socket.io

In order to associate the users with their sockets, most sites are suggesting something like this:

4条回答
  •  礼貌的吻别
    2021-02-09 23:59

    var people will be accessible on the same process.

    When you want to scale with multiple socket server and balancing between them, then this idea for keeping people object locally will be not helpful.

    Create authenticate event for authentication and set socket.userId and socket.isAuthenticate = true flag. In other events if socket.isAuthenticate is false, kick them out.

    Make use of 'socket.io-redis' adpater for communication among many socket.io server. ( So when user1 from server1 send message to user2 which is in server2, will work ).

    For socket - user association with multiple process, you can join Room with their userId, on authentication, join room like socket.join('myuserId');

    and when to send message to that user, you can use io.to('myuserId').emit('message', "Hi How are you?"):

提交回复
热议问题