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?
-
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)Denys Séguret– Denys Séguret2016-04-29 06:49:48 +00:00Commented Apr 29, 2016 at 6:49
-
@NKMY did you try anything yet? Or you want to know how socket works?Sk Arif– Sk Arif2016-04-29 06:55:16 +00:00Commented 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.Phagun Baya– Phagun Baya2016-04-29 07:09:18 +00:00Commented Apr 29, 2016 at 7:09
Add a comment
|
1 Answer
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));
3 Comments
NKMY
Thanks for your help. Do u know any reference or example of utility class for this socket notifications is provided.
NKMY
Thanks @risuch for the link.