Node js multiple routes get socket

2019-08-14 15:10发布

问题:

I am using NodeJS, socket.io and express to create an application and I am wondering how can I determinate which socket (id/user) is on which router? For example I have 10 users on my website, and I have 3 routes: /home, /about, /contact. How can I know which user is on which router?

回答1:

Firstly to know "which user" itself you'll need a system with sessions and cookies to identify a particular user each time they make a different request. Passport.JS makes this really easy.

Secondly to share this same user among Express route and Socket.io handler would require sharing the session information between the two. For Passport.js there's socket.io-passport that does this.

Lastly, when client-side Socket.io initiates a connection request to the server by io.connect() it sets the referrer header of the request to current URL, which can be accessed on server-side with socket.request.headers.referer

With all that in place you'll finally be able to tell which user is on which route:

app.get('/about', function(req, res, next){
    // req.user is on '/about' path
});
var URL = require('url');
io.on('connection', function(socket) {
    var user = socket.request.user;
    var path = URL.parse(socket.request.headers.referer).path;
    // user is on -> path
});