我正在尝试添加通知系统。如果用户登录并执行操作,则应在其登录时将通知发送给另一个用户。我已使用express在node.js中创建了我的应用程序。我知道我必须使用套接字,但需要如何处理事件?如果有人可以让我知道我可以为此任务遵循的任何参考或样本?
答案 0 :(得分:1)
我刚刚做了类似的事情并按照这样处理:
io.js - 我处理新连接并存储io的中心node.js文件
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 - 在node.js服务器应用程序的某个地方,我想发出消息
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 - 一些客户端js(在我看来是有角度的,但它确实很重要),导入socket.io lib,然后像这样访问客户端的某个地方:
/*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));