我正在尝试添加通知系统。如果用户登录并执行操作,则应将通知发送给已登录的另一个用户。我已经使用express在node.js中创建了我的应用程序。我知道我必须使用套接字,但是需要如何处理事件?如果有人可以让我知道我可以遵循此任务的任何引用或样本?
最佳答案
我刚刚做了类似的事情并这样处理:
io.js - 中央 node.js 文件,我在其中处理新连接并存储 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 - 我想在 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));
关于node.js - 使用node.js、express、socket实现通知系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931311/