socket.io authentification不能在第一次连接时工作

时间:2017-01-14 05:25:45

标签: javascript node.js socket.io jwt node-webkit

我有一个NodeWebkit客户端,它使用socket.io库(JavaScript)连接到nodejs服务器。

客户端在应用程序启动时启动连接过程,但服务器不会确认任何连接...虽然客户端的套接字具有连接属性" true"。

你应该知道我正在使用socketio-jwt来验证连接。
Github:https://github.com/auth0/socketio-jwt

我知道连接确实有效,因为如果我添加:

io.sockets.on('connection', function(){console.log("hello");})

打印你好!

所以似乎事件通过连接以某种方式使它不想与库进行auth部分,导致......嗯......没什么。

但那不是全部!!
因为如果我重新启动应用程序(而不是服务器),那么auth大部分时间都可以工作!它就像一个竞争条件...但我不知道它怎么可能是一个...每一个代码行正在执行成功回调验证。

我尝试连接到远程服务器和我的localhost。 我也尝试过使用socket auth的其他库,但我遇到了同样的问题。

这是服务器代码:

var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');

io.sockets.on('connection', socketioJwt.authorize({
    secret: 'some secret',
    timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {

   console.log('[Info]: A user connected to socket = ', socket.decoded_token);

});
});



http.listen(5000, function () {
      console.log('listening on *:5000');
});

现在客户端代码:

this.socket = io.connect('http://' + that.hostName +':' + that.port);     
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret); 

this.socket.on('connect', function () {
    that.socket.emit('authenticate', {token: token}) //send the jwt
            .on('authenticated', function () {

                console.log("[Info]: Socket login successfull");

            })
            .on('unauthorized', function (msg) {
                console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
                throw new Error(msg.data.type);
            });
});

服务器端日志"连接到套接字的用户"从未显示过。
如果你有一个想法!谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

为什么有'在socket.emit(客户端)?我认为你应该在socket.io的同一个实例中处理它 - 使用相同的'这个'如上所述