Send update notification to particular users using socket.io

前端 未结 2 1923
梦谈多话
梦谈多话 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:48

    According to what i understand, you need private notification send to only some users. For that, save your users name to whom you want to send and their corresponding socket in different hashes.

    username [socket.name] = username to be added;
    usersocket [ socket.name ] =socket;
    

    Then to emit the messages to that user only, use

    usersocket[ socket.name ].emit('event for send message', ' what you want to send ');
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题