gpt4 book ai didi

node.js - 如何将更改从中间件传递到 socket.io?

转载 作者:搜寻专家 更新时间:2023-10-31 23:43:22 24 4
gpt4 key购买 nike

我正在使用 node.js 和 socket.io 向用户推送实时通知。但是,目前我只是发回在我的 socket.io 代码中完成的查询结果并将其发送回客户端,但我需要让 socket 知道发生的更改并更新更改或重新查询数据库检查新号码并将其发送给客户端。

例如,如果用户收到好友请求,则通知计数将发生变化,我希望 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是文件可用的全局变量

最佳答案

我帮助他离线解决了这个问题,但我们最终使用了 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 );
};

关于node.js - 如何将更改从中间件传递到 socket.io?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18664184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com