6

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++;
    }
};

2 Answers 2

20
+25

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.

1
  • 1
    Please find my edit..I am not getting automatic update on client side..I have to refresh browser then only update reflects
    – Trialcoder
    Oct 13, 2014 at 12:15
3

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 ');
2
  • yeah sure let me just bind files for you
    – Trialcoder
    Oct 14, 2014 at 6:50
  • I saw your edit but I dont see any mistake in it. Try using connect instead of connection coz connection is a reserved event. And don't forget to change the event name in server too. Oct 14, 2014 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.