如何将中间件更改传递给socket.io? [英] How to pass changes from middleware to socket.io?
问题描述
我正在使用带有socket.io的node.js来向用户推送实时通知。但是,目前我只是发回在我的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('脉冲',{heartbeat:new Date()。toString(),timestamp:new Date()。getTime()})
},300 * 1000)
套接字.on('disconnect',function(){
console.log('socket:du mp'+ 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' {通知:通知});
});
});
这是客户端:
div#CheckSocket
脚本(src ='http:// localhost:3000 / socket.io / socket.io.js')
脚本。
$(document).ready(function(){
console.log('socket');
var socket = io.connect('http:// localhost: 3000 /');
console.log('entered1');
socket.on('entrance',function(data){
console.log );
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输入2');
});
函数setStatus(msg){
console.log('connection status:'+ ms g);
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(save it);
success = true;
}
});
回调(null,success)
}
function(success,callback){
// if(success === true){
var success2;
var newFriend2 = n ew 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;
}
});
回调(null,success2);
//} else {
// res.send(request 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){
//启用邮件并包含一般您有新请求...不包括名称,因为不存储
}
}
success 3 = true;
callback(null,success3);
}],
函数(err,results){
res.json响应:true});
console.log(添加成功);
});
};
注意:dbnotif是一个由mongoose调用的模型,
userID是一个全局变量到文件
我帮助他离线解决了这个问题,但我们最终使用EventEmitter作为代理。 >
// main.js
var EventEmitter = require('events')。EventEmitter;
var emitter = new EventEmitter();
然后将其添加到每个请求作为中间件:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
next();
});
然后在外部路由文件中:
// routes.js
exports.addContactPost = function(req,res,err){
req.emitter.emit('some-key' ,无论什么,数据,你,想);
};
I am using node.js with socket.io to push real time notifications to users. However, currently I am just sending back a query result done in my socket.io code and sending it back to the client but I need to let socket know about the changes that occur and to either update with the changes or re-query the db to check for the new number and send that to the client.
For example if a user gets a friend request then the notification count will change and I want socket.io to push the new notification count number to the user.
here is my socket.io code in my app.js file:
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});
});
});
Here is the client side:
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');
}
});
Here is the example of adding a friend in the route file:
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");
});
};
Notes: dbnotif is a model being called by mongoose, userID is a global variable available to the file
I helped him solve this question offline, but we ended up using an EventEmitter as a proxy.
// main.js
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
Then add it to each request as middleware:
// elsewhere in main.js
app.use(function(req, res, next) {
req.emitter = emitter;
next();
});
Then in external routes file:
// routes.js
exports.addContactPost = function(req, res, err) {
req.emitter.emit( 'some-key', whatever, data, you, want );
};
这篇关于如何将中间件更改传递给socket.io?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!