I'm trying to hookup a front-end server to our notification service, and then the front-end server to the browser. The notification service is realtime, and includes the recipients user id in the sent notification data. I'm not having problems with the notification service sending the data and the front-end server receiving it. And I can have it connect and disconnect to the browser just fine, like this:
io.on('connection', function (socket) {
console.log('connected');
socket.on('disconnect', function () {
console.log('disconnected');
});
});
I need to now know what user is signed in to the front-end server so I know which user/socket to send the notification to. We can get this data from our express session if I put the connection listener in a middleware function like so:
var allClients = {};
function useSocket (req, res, next) {
io.on('connection', function (socket) {
allClients[req.session.userId] = socket;
socket.on('disconnect', function () {
console.log('disconnected');
allClients[req.session.userId].removeAllListeners();
// we were also suggested things like socket.close() which did not help
});
});
next();
}
app.get('*', useSocket, function (req, res){
res.render('../views/index');
});
except the code above creates a new connection on every browser refresh, so a user gets a dupe notification for as many times as any browser has connected.
This is my code that talks to the notification service:
var notificationServiceSocket = require('socket.io-client').connect(notificationServiceUrl);
notificationServiceSocket.on('notification', function (data) {
// data.user_id is the intended recipient
});
How can I determine which socket is related to the recipient without creating infinite connections?
Aucun commentaire:
Enregistrer un commentaire