这里真正的答案是使用SocketIO 框架中所谓的handshake。它允许您进行一些检查并决定是否应该允许用户连接到您的服务器。周围的其他答案根本不会自动允许用户连接。但是,如果他只打开一个控制台并针对您的服务器实例化套接字 - 他就在线。
看看这个:http://socket.io/docs/server-api/#namespace#use(fn:function):namespace
在每次连接尝试时,您都可以运行特定函数来查看是否正常。然后,您可以拒绝连接(使用参数调用 next),或接受它 - 只需调用 next。
就是这样:)
但棘手的部分来了——如何真正验证用户身份?每个套接字都使用来自客户端的简单 HTTP 请求进行实例化。后来升级为socket连接。
如果您使用某种数据库或会话,您可以使用其中的许多模块。我一直在使用护照,所以一切都会自动发生。以下是有关如何操作的更多信息:https://github.com/jfromaniello/passport.socketio
var io = require("socket.io")(server),
sessionStore = require('awesomeSessionStore'), // find a working session store (have a look at the readme)
passportSocketIo = require("passport.socketio");
io.use(passportSocketIo.authorize({
cookieParser: cookieParser, // the same middleware you registrer in express
key: 'express.sid', // the name of the cookie where express/connect stores its session_id
secret: 'session_secret', // the session_secret to parse the cookie
store: sessionStore, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
function onAuthorizeSuccess(data, accept){
console.log('successful connection to socket.io');
// The accept-callback still allows us to decide whether to
// accept the connection or not.
accept(null, true);
// OR
// If you use socket.io@1.X the callback looks different
accept();
}
function onAuthorizeFail(data, message, error, accept){
if(error)
throw new Error(message);
console.log('failed connection to socket.io:', message);
// We use this callback to log all of our failed connections.
accept(null, false);
// OR
// If you use socket.io@1.X the callback looks different
// If you don't want to accept the connection
if(error)
accept(new Error(message));
// this error will be sent to the user as a special error-package
// see: http://socket.io/docs/client-api/#socket > error-object
}