Win*_*ade 57 node.js handshake socket.io
所以我有一个应用程序运行节点js,socket.io作为后端,普通的javascript作为前端.我的应用程序有一个登录系统,目前只需让客户端在连接后立即发送其登录数据.
现在我认为将登录数据与handshakeData一起发送会更好,因此我可以在连接时(而不是在建立连接之后)直接让用户登录,在登录数据无效时分别拒绝授权.
我认为最好将我的附加数据放在handshakeData的标题部分,所以任何想法我怎么能这样做?(如果可能的话,无需修改socket.io,但如果这是我可以忍受的唯一方式)
Ale*_*ght 138
正如下面许多评论所指出的那样,Socket.IO API在1.0
发布时发生了变化.现在应通过中间件功能进行身份验证,请参阅"身份验证差异"@ 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" });
Run Code Online (Sandbox Code Playgroud)
服务器端:
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'));
});
Run Code Online (Sandbox Code Playgroud)
您可以在客户端的第二个参数中传递查询:param到connect(),这将在授权方法中的服务器上可用.
我刚刚测试过它.在客户端我有:
var c = io.connect('http://127.0.0.1:3000/', { query: "foo=bar" });
Run Code Online (Sandbox Code Playgroud)
在服务器上:
io.set('authorization', function (handshakeData, cb) {
console.log('Auth: ', handshakeData.query);
cb(null, true);
});
Run Code Online (Sandbox Code Playgroud)
然后服务器上的输出看起来像:
:!node node_app/main.js
info - socket.io started
Auth: { foo: 'bar', t: '1355859917678' }
Run Code Online (Sandbox Code Playgroud)
slu*_*013 19
现在已在v1.0.0中进行了更改.请参阅迁移文档
基本上,
io.set('authorization', function (handshakeData, callback) {
// make sure the handshake data looks good
callback(null, true); // error first, 'authorized' boolean second
});
Run Code Online (Sandbox Code Playgroud)
成为:
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();
});
Run Code Online (Sandbox Code Playgroud)
zay*_*tro 10
对于socket.io v1.2.1,请使用:
io.use(function (socket, next) {
var handshake = socket.handshake;
console.log(handshake.query);
next();
});
Run Code Online (Sandbox Code Playgroud)
小智 7
这是我的代码,用于向nodejs和server.io服务器客户端发送查询数据.
var socket = io.connect(window.location.origin, { query: 'loggeduser=user1' });
io.sockets.on('connection', function (socket) {
var endp = socket.manager.handshaken[socket.id].address;
console.log("query... " + socket.manager.handshaken[socket.id].query.user);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53558 次 |
最近记录: |