【问题标题】:Socket.IO Handshake AuthorizationSocket.IO 握手授权
【发布时间】:2017-06-22 21:50:30
【问题描述】:

我在我的 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 事件中发送一条消息,指示无效凭据,然后终止连接。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2013-10-07
      • 2015-06-06
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多