提问者:小点点

将自定义数据与Socket.io中的handshakeData一起发送?


所以我有一个运行node js的应用程序,socket.io作为后端,普通javascript作为前端。我的应用程序有一个登录系统,它目前只是让客户端在连接后立即发送其登录数据。

现在我想让登录数据和握手数据一起发送会更好,这样我就可以直接让用户在连接时登录(而不是在建立连接之后),当登录数据无效时分别拒绝授权。

我在想最好是把我的附加数据放在handshakeData的头部分,所以有什么想法我可以这样做吗?(如果可能的话,不需要修改socket.io,但如果这是我能接受它的唯一方法的话)


共3个答案

匿名用户

正如下面的许多评论所指出的,socket.io API在1.0发行版中发生了变化。身份验证现在应该通过一个中间件函数来完成,请参见“Authentication Differences”@http://socket.io/docs/migrating-from-0-9/#Authentication-Differences。我将提供我的原始答案,供任何坚持<1.0的人使用,因为旧的文档似乎已经消失了。

客户端:

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

您可以将第二个参数中的query:param传递给客户端上的connect(),该参数将在服务器上的authorization方法中可用。

我只是在测试。关于我的客户:

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' }

匿名用户

这在V1.0.0中已经更改。请参阅迁移文档

基本上,

io.set('authorization', function (handshakeData, callback) {
  // make sure the handshake data looks good
  callback(null, true); // error first, 'authorized' boolean second 
});

变成:

  io.use(function(socket, next) {
  var handshakeData = socket.request;
  // make sure the handshake data looks good as before
  // if error do this:
    // next(new Error('not authorized');
  // else just call next
  next();
});

匿名用户

对于Socket.IO v1.2.1,请使用以下命令:

io.use(function (socket, next) {
  var handshake = socket.handshake;
  console.log(handshake.query);
  next();
});