节点js多个路由获取套接字 [英] Node js multiple routes get socket

查看:83
本文介绍了节点js多个路由获取套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NodeJS,socket.io和express创建一个应用程序,我想知道如何确定哪个路由器(id/用户)在哪个路由器上? 例如,我的网站上有10个用户,并且有3条路由:/home,/about,/contact.我怎么知道哪个用户在哪个路由器上?

解决方案

首先要了解哪个用户"本身,您将需要一个具有会话和cookie的系统,以便在他们每次提出不同请求时标识特定用户. Passport.JS 使此操作非常容易.

第二,要在Express路由和Socket.io处理程序之间共享同一用户,将需要在两者之间共享会话信息.对于Passport.js,可以使用 socket.io-passport 来完成.

最后,当客户端Socket.io通过io.connect()发起到服务器的连接请求时,它将请求的引荐来源标头设置为当前URL,可以在服务器端使用socket.request.headers.referer

有了这一切,您最终将能够分辨出哪个用户在哪个路线上:

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
});

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?

解决方案

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
});

这篇关于节点js多个路由获取套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆