这是服务器代码:
io.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
app.post('/login', function (req, res)
{
if((req.body.username === "test") && (req.body.password === "test"))
{
var token = jwt.sign({ username: req.body.username, password: req.body.password}, jwtSecret, { expiresInMinutes: 60*24*7 });
res.json({ token: token });
console.log(req.body.username + " logged in");
}
else
{
res.status(401).send('Wrong user or password');
}
});
io.on('connection', function(socket)
{
// test event
socket.on('ping', function (data)
{
io.emit("pong", data)
});
});
在这里客户:
var server = $("#server-input").val();
var obj = { username: $("#login-input").val(), password: $("#password-input").val() };
$.post(server + "/login", obj)
.done( function(response)
{
connect_socket(response.token);
});
function connect_socket(token)
{
socket = io(server, {query: 'token=' + token});
socket.on("connect", function()
{
socket.emit("ping", {hi:"there"});
socket.on("pong", function(data)
{
console.log(data);
});
});
}
现在,当一个用户连接时,ping将被发送并被接收。当同一个用户第二次连接时,将在两个实例上接收pong,但是当另一个用户连接时,只有该用户才能看到pong。用户a和b看不到彼此。
我该如何解决这个问题?这可能是身份验证的问题吗?