如何将中间件的更改传递给socket.io?

我正在使用node.jssocket.io推送实时通知给用户。 但是,目前我只是发送一个查询结果在我的socket.io代码完成,并发送回客户端,但我需要让套接字知道发生的变化,要么更新与更改或重新查询数据库检查新号码并将其发送给客户。

例如,如果用户获得好友请求,那么通知计数将会改变,我希望socket.io将新的通知计数编号推送给用户。

这里是我的app.js文件中的socket.io代码:

io.on('connection', function(socket) { var sessionID = socket.handshake.sessionID, session = new connect.middleware.session.Session({ sessionStore: sessionStore }, socket.handshake.session) console.log('socket: new ' + sessionID) socket.broadcast.emit('arpNewConn', session.passport.user) var intervalID = setInterval(function() { socket.handshake.session.reload(function() { socket.handshake.session.touch().save() }) socket.emit('pulse', { heartbeat: new Date().toString(), timestamp: new Date().getTime() }) }, 300 * 1000) socket.on('disconnect', function() { console.log('socket: dump ' + sessionID) socket.broadcast.emit('arpLostConn', session.passport.user) clearInterval(intervalID) }) socket.emit('entrance', {message: 'Message works'}); dbnotif.findOne(userID, function (err, user) { if(err) throw err; notify = user.notifications; socket.emit('notify', {notific: notify}); }); }); 

这里是客户端:

 div#CheckSocket script(src='http://localhost:3000/socket.io/socket.io.js') script. $(document).ready(function () { console.log('socket'); var socket = io.connect('http://localhost:3000/'); console.log('entered1'); socket.on('entrance', function (data) { console.log('entered'); console.log(data.message); }); socket.on('notify', function (data) { console.log('noting'); console.log(data.notific); if(data.notific !== 0) $('.notifications').html(data.notific); }); socket.on('reconnecting', function(data) { setStatus('reconnecting'); console.log('entered2'); }); function setStatus(msg) { console.log('connection status: ' + msg); console.log('entered5'); } }); 

以下是在路由文件中添加好友的示例:

 exports.addContactPost = function(req, res, err) { async.waterfall([ function(callback) { var success; var newFriend = new Friend ({ userId: req.signedCookies.userid, friend_id: mongoose.Types.ObjectId(req.body.otherUser), friend_status: 1 }); newFriend.save(function(err){ if(err) { console.log(err); } else { console.log("saved it"); success = true; } }); callback(null, success) }, function(success, callback) { //if(success === true) { var success2; var newFriend2 = new Friend ({ userId: mongoose.Types.ObjectId(req.body.otherUser), friend_id: req.signedCookies.userid, friend_status: 2 }); newFriend2.save(function(err){ if(err) { res.send("request not received"); } else { success2 = true; } }); callback(null, success2); //} else { // res.send("error with request sent"); //} }, function(success2, callback) { console.log('callback3'); //if(success2 === true) { var success3; Notification.findOneAndUpdate({userId: mongoose.Types.ObjectId(req.body.otherUser)}, { $inc: {notifications: 1} }, function(err, notify) { if(err) { res.send(err); } else { console.log(notify); if(notify.added_notifications === true) { // enable mail and include general u have got a new request... do not include name because not storing it } } success3 = true; callback(null, success3); }], function(err, results) { res.json({response: true}); console.log("Add successful"); }); }; 

注意:dbnotif是被mongoose调用的模型,userID是文件可用的全局variables

       

网上收集的解决方案 "如何将中间件的更改传递给socket.io?"

我帮他离线解决了这个问题,但是最后我们用EventEmitter作为代理。

 // main.js var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); 

然后将其作为中间件添加到每个请求中:

 // elsewhere in main.js app.use(function(req, res, next) { req.emitter = emitter; next(); }); 

然后在外部路由文件中:

 // routes.js exports.addContactPost = function(req, res, err) { req.emitter.emit( 'some-key', whatever, data, you, want ); };