Socket.io会话没有express.js?

我想通过node.js和socket.io来处理websocket的会话,而不必使用cookie并避免express.js,因为还应该有客户端不在浏览器环境中运行。 有人已经这样做了,或者有了一些概念validation的经验?

在socket.io连接build立之前,有一个握手机制,默认情况下,所有正确的传入请求成功握手。 然而,有一种方法可以在握手过程中获取套接字数据,并根据您的select返回true或false,从而接受或拒绝传入的连接请求。 这里是来自socket.io文档的例子:

由于handshakeData是在授权后存储的,所以您实际上可以从该对象中添加或删除数据。

var io = require('socket.io').listen(80); io.configure(function (){ io.set('authorization', function (handshakeData, callback) { // findDatabyip is an async example function findDatabyIP(handshakeData.address.address, function (err, data) { if (err) return callback(err); if (data.authorized) { handshakeData.foo = 'bar'; for(var prop in data) handshakeData[prop] = data[prop]; callback(null, true); } else { callback(null, false); } }) }); }); 

callback函数的第一个参数是错误的,你可以在这里提供一个string,如果没有设置为null,它会自动拒绝客户端。 第二个参数是布尔值,是否要接受传入的请求。

这应该是有帮助的, https://github.com/LearnBoost/socket.io/wiki/Authorizing

您可以跟踪所有会话variables,并使用handshakeData中的以下可用组合来唯一标识用户

 { headers: req.headers // <Object> the headers of the request , time: (new Date) +'' // <String> date time of the connection , address: socket.address() // <Object> remoteAddress and remotePort object , xdomain: !!headers.origin // <Boolean> was it a cross domain request? , secure: socket.secure // <Boolean> https connection , issued: +date // <Number> EPOCH of when the handshake was created , url: request.url // <String> the entrance path of the request , query: data.query // <Object> the result of url.parse().query or a empty object } 

这个例子也可能有帮助,只要你的非浏览器客户端以不同的方式提供信息:

SocketIO + MySQLauthentication