Socket.IO握手授权

时间:2017-02-06 02:26:06

标签: javascript node.js sockets websocket socket.io

我的NodeJS服务器中有以下内容,以确保在连接请求的握手中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") {
        console.log("Got auth params.");
        socket.emit('chat message','Valid credentials.');
        return next();
    }
    // call next() with an Error if you need to reject the connection.
    console.log("Didn't get auth params.");
    socket.emit('chat message','Invalid credentials.');
    next(new Error('Authentication error'));
});

当握手数据中的foo=bar时,chat message表示“有效凭据”。已成功发送给客户端。但是,当foo!=bar socket.emit未发出“无效凭据”时。聊天消息。

是否可以在foo!=bar的情况下向请求连接的客户端发送消息?

我假设向客户端发送消息以响应其连接请求的唯一方法是接受与return next()的连接,在connection事件中发送消息指示无效的凭据,然后终止连接。

1 个答案:

答案 0 :(得分:0)

为了捕获通过next(new Error('Authentication error'))发出的错误消息,只需在客户端为error事件创建一个处理程序:

socket.on('error', function(err){
  console.log('Connection Failed: ' + err);
});