发送自定义数据以及socket.io中的handshakeData吗? [英] Send custom data along with handshakeData in socket.io?

查看:535
本文介绍了发送自定义数据以及socket.io中的handshakeData吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个应用程序运行节点js,其中socket.io作为后端,普通javascript作为前端.我的应用程序有一个登录系统,当前该系统只是让客户端在连接后立即发送其登录数据.

So I have an application running node js with socket.io as a backend and normal javascript as frontend. My application has a login system which currently simply has the client send its login data as soon as it's connected.

现在,我认为将登录数据与handhakeData一起发送会更好,因此我可以直接在连接时(而不是在建立连接之后)使用户登录(而不是在建立连接之后),然后在登录数据无效时拒绝授权

Now I figured it would be much nicer to have the login data sent along with the handshakeData, so I can directly have the user logged in while connecting (instead of after establishing a connection) respectively refuse authorization when the login data is invalid.

我认为最好将其他数据放在handshakeData的标头部分中,所以有什么想法可以做到这一点? (如果可能的话,不必修改socket.io,但是如果这是我可以使用的唯一方法)

I'm thinking it would be best to put my additional data in the header part of the handshakeData, so any ideas how I could do that? (Without having to modify socket.io if possible, but if it's the only way I can live with it)

推荐答案

正如下面的许多评论所指出的那样,Socket.IO API在其1.0版本中进行了更改.现在应该通过中间件功能进行身份验证,请参阅身份验证差异" @ http://socket .io/docs/migrating-from-0-9/#authentication-differences .对于旧文档似乎不见了的所有停留在< 1.0之上的人,我都会提供我的原始答案.

As a lot of comments have pointed out below the Socket.IO API changed in their 1.0 release. Authentication should now be done via a middleware function, see 'Authentication differences' @ http://socket.io/docs/migrating-from-0-9/#authentication-differences. I'll include my orginal answer for anyone stuck on <1.0 as the old docs seem to be gone.

客户端:

//The query member of the options object is passed to the server on connection and parsed as a CGI style Querystring.
var socket = io("http://127.0.0.1:3000/", { query: "foo=bar" });

服务器端:

io.use(function(socket, next){
    console.log("Query: ", socket.handshake.query);
    // return the result of next() to accept the connection.
    if (socket.handshake.query.foo == "bar") {
        return next();
    }
    // call next() with an Error if you need to reject the connection.
    next(new Error('Authentication error'));
});

1.0之前版本

您可以传递一个查询:客户端第二个参数中的param到客户端的connect(),它将在服务器上的授权方法中可用.

Pre 1.0

You can pass a query: param in the second argument to connect() on the client side which will be available on the server in the authorization method.

我刚刚对其进行了测试.在客户端上,我有:

I've just been testing it. On the client I have:

var c = io.connect('http://127.0.0.1:3000/', { query: "foo=bar" });

在服务器上:

io.set('authorization', function (handshakeData, cb) {
    console.log('Auth: ', handshakeData.query);
    cb(null, true);
});

服务器上的输出如下:

:!node node_app/main.js
   info  - socket.io started
Auth:  { foo: 'bar', t: '1355859917678' }

这篇关于发送自定义数据以及socket.io中的handshakeData吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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