Send update notification to particular users using socket.io

你离开我真会死。 提交于 2020-05-09 18:55:54

问题


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

FYI - Node Version 1.1.0

// Socket Notification
var socket = io('http://localhost:6868');
socket.on('connection', function (data) {
    socket.emit('send notification', { sent_to: storeSelUserId });
});

Following is the server code in routes file -

var clients = {};  
io.on('connection', function (socket) {
  socket.emit('connection', "Connection Created.");
  socket.on('send notification', function (sent_to) {
    console.log(sent_to);
  });
});

In console sent_to is showing the array of user_id.

Now being a starter in socket.io I stuck with the solution that how do I send the message to these particular userids.

I search and found that I need to push each user with its sockets so I reformed it to -

var users = [];  
io.on('connection', function (socket) {
  users.push({socket_id: socket.id});
  socket.emit('connection', "Connection Created.");
  socket.on('send notification', function (sent_to) {
    console.log(sent_to);
  });
});

But I am in dilemma that else do I need to do to store which user_id refers to which socket_id and then update the div of users with that particular ids?

EDIT -

Add Controller - (Front End)

Front end Interface where memo is created and send to particular users

var socket = io('http://localhost:6868');
socket.on('connection', function (data) {
    socket.emit('send memo notification', {creator_id: creator_id, sent_to: [Array of user_ids to whom memo to send]});
});

Dashboard controller - (Front End)

Front end Interface where notification count to show "notificationCount"

if (SessionService.currentUser._id) {
    var socket = io('http://localhost:6868');
    socket.on('connection', function (data) {
        socket.emit('get notifications', {user_id: SessionService.currentUser._id});
    });

    socket.on('notification data', function(data){
        console.log("-- Not Data Test -");
        $scope.notificationCount = data.length;
    });
}

Code at server end -

io.on('connection', function (socket) {

  socket.emit('connection', "Connection Created.");

  socket.on('send memo notification', function(data) {
        notifications.createNotification(data);
  });

  socket.on('get notifications', function(data){
    notifications.getNotifications(data, function(response){
        socket.emit('notification data', response.data);
    });
  });

});

Backend controller code -

exports.getNotifications = function(data, callback) {
    var userId = data.user_id;
    Notification.find({receiver_id: userId}, function(err, response){
        if (err)
            callback({"message": "error", "data": err, "status_code": "500"});
        else
            callback({"message": "success", "data": response, "status_code": "200"});
    });  
};

exports.createNotification = function(data) {
    var notificationData = data;
    var x = 0;
    for(var i=0; i< notificationData.length; i++) {
        // Code
        Notification(notificationData[i]).save(function(err,response){
            if (err)
                return false;
        });    
        if (x === notificationData.length - 1) {
            return true;
        }
        x++;
    }
};

回答1:


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.




回答2:


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 ');


来源:https://stackoverflow.com/questions/26297373/send-update-notification-to-particular-users-using-socket-io

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