尝试使用套接字对象的断开连接方法,如下所示:
io.on('connection', function(socket){
//temp delete socket
socket.disconnect();
console.log(io.sockets.connected);
socket.emit("test");
});
UPDATE:
例如,如果您的 HTTP 服务器向客户端提供令牌:
app.post('/api/users', function (req, res) {
var user = {
username: req.body.username
};
var token = jwt.sign(user, secret, {expiresInMinutes: 30});
res.json({token: token});
});
然后您可以重复使用该令牌来验证您的 websocket 连接。
从客户端(html 文件)发送令牌的代码将是:
socket = io.connect('http://localhost:4000', {
query: 'token=' + validToken,
forceNew: true
});
服务器(socketio)中的socketio授权代码将是:
// here is being used a socketio middleware to validate
// the token that has been sent
// and if the token is valid, then the io.on(connection, ..) statement below is executed
// thus the socket is connected to the websocket server.
io.use(require('socketio-jwt').authorize({
secret: secret,
handshake: true
}));
// but if the token is not valid, an error is triggered to the client
// the socket won't be connected to the websocket server.
io.on('connection', function (socket) {
console.log('socket connected');
});
请注意,express 上使用的秘密用于生成令牌,socketio 中间件的验证令牌也使用相同的令牌。
我创建了一个示例,您可以在其中看到这种验证是如何工作的,源代码在这里:https://gist.github.com/wilsonbalderrama/a2fa66b4d2b6eca05a5d https://gist.github.com/wilsonbalderrama/a2fa66b4d2b6eca05a5d
将它们复制到文件夹中并使用 Node 运行 server.js,然后通过浏览器访问以下 URL 的 html 文件:http://本地主机:4000 http://localhost:4000
但首先安装模块:socket.io、express、socketio-jwt、jsonwebtoken