我使用下面的代码检测客户端何时连接到服务器并为该客户端分配套接字:
// setup
const io = require('socket.io')(server);
io.sockets.on('connection', socket => { // client is connecting to server });
断开连接时将检测什么代码?我会假设像这样,但我不确定。
io.sockets.on('disconnect', socket => { // client is disconnecting from the server });
更好的是,它将是io.sockets
答案 0 :(得分:1)
请确保您正在侦听绑定到disconnect
事件的函数中socket
参数上的connection
事件。
// setup
const io = require('socket.io')(server);
io.sockets.on('connection', socket => {
// client is connecting to server
socket.on('disconnect', reason => {
// client is disconnecting from the server
});
});
文档可在此处找到:https://socket.io/docs/server-api/#Event-'disconnect'
答案 1 :(得分:1)