Send update notification to particular users using socket.io

前端 未结 2 1961
梦谈多话
梦谈多话 2021-02-02 04:38

Following is the code on front end, where storeSelUserId contains user_id to send the message-

FYI - Node Version 1.1.0

//          


        
2条回答
  •  半阙折子戏
    2021-02-02 04:53

    If you want to use your own user ids then there is no way around mapping the socket id to the user id. I assume a client knows its user id from somewhere, so it could send its user id to the server after connection.

    Client

    socket.on('connection', function (data) {
        socket.emit('setUserId', myUserId);
    });
    

    The server saves the socket for each user id.

    socket.on('setUserId', function (userId) {
        users[userId]=socket;
    });
    

    If you have such a mapping in the server you can send a message just to this client using the user id.

    socket.on('send notification', function (userId) {
         users[userId].emit('notification', "important notification message");
    });
    

    Edit: Saving the corresponding socket directly is even better.

提交回复
热议问题