1

I am trying to add a notification system. If a user logs in and performs an action a notification should be sent to another user if he is logged in. I have made my application in node.js using express. I know that I have to use socket but how the event needs to be handled? If someone could let me know any reference or sample which I can follow for this task?

3
  • It's not clear what part is missing. In my chat the event is handled by a socket.io client and I use the Notification API to display it to the user (relevant code) Commented Apr 29, 2016 at 6:49
  • @NKMY did you try anything yet? Or you want to know how socket works? Commented Apr 29, 2016 at 6:55
  • You can read this as a reference gianlucaguarini.com/blog/… In short, you need to maintain the global list of users online and their respective socket connection. So, whenever a user makes any action you can use the global list to select your targeted user. Commented Apr 29, 2016 at 7:09

1 Answer 1

3

I just did something similar and handled it like this:

io.js - central node.js file where I handle new connnections and store io

var io = require('socket.io')();

io.on('connection', function(socket){
 console.log("Socket established with id: " + socket.id);

 socket.on('disconnect', function () {
  console.log("Socket disconnected: " + socket.id);
 });

});

module.exports = io;

someroute.js - somewhere in the node.js server application I want to emit messages

var appRoot = require('app-root-path');
var io = require(appRoot + '/server/io');

/*your code, somwhere you will call the
 * function below whenever you want to emit
 * the 'user_did_action' event:
*/
if(user.didNewStuff()){
 emitUserAction(user);
}

var emitUserAction = function(user){
  io.sockets.emit('user_did_action', user);
};

client_javascript.js - some client js (in my case angular, but it doesent matter), import the socket.io lib, then access somewhere in the client like this:

/*connect to the server*/
var socket = io.connect();

/*do something wen the event 'user_did_action'
 * is received, just invoke the callback
 *
 *in the function param data, you will have the same
 *data you emitted earlier in the server, 
 *in this example the user object!*/
socket.on('user_did_action', myFunctionToHandleTheEvent(data));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help. Do u know any reference or example of utility class for this socket notifications is provided.
Here you can find a quite elaborate tutorial/example of a notification application using node.js and socket.io
Thanks @risuch for the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.