gpt4 book ai didi

javascript - 当客户端调用断开连接时,Socket.io 服务器未收到 'disconnect' 事件

转载 作者:行者123 更新时间:2023-12-01 03:08:47 26 4
gpt4 key购买 nike

我正在node.js(客户端和服务器)上使用socket.io,并且在“断开连接”事件方面遇到问题。看一下下面的摩卡测试代码:

it('This test never finishes', function(done) {
// Output:
// connected socket iYTGdwMJ0yVM5orGAAAB

io.on('connection', (socket) => {
console.log('connected socket', socket.id);
socket.on('disconnect', () => {
console.log('io disconnect');
done();
});
});

const mj = ioClient(`https://localhost:${socketPort}`);

mj.on('disconnect', () => {
console.log('mj disconnect');
});

mj.disconnect();
});

it('This test works', function(done) {
// Output:
// connected socket DNUREuytEp1CPJdFAAAC
// io disconnect

io.on('connection', (socket) => {
console.log('connected socket', socket.id);
console.log(io.socket.connected);
socket.on('disconnect', () => {
console.log('io disconnect');
done();
});
socket.disconnect();
});

const mj = ioClient(`https://localhost:${socketPort}`);

mj.on('disconnect', () => {
console.log('mj disconnect');
});

// Looks like this has no effect
mj.disconnect();
});

当客户端调用disconnect时,为什么服务端没有触发socket.on('disconnect', ...)监听器?

最佳答案

我认为这是一个典型的同步性问题(阅读代码注释中的解释)。

// This code will try to connect the server - 
// but the connection process is asynchronous
const mj = ioClient(`https://localhost:${socketPort}`);

// Now you subscribe to the disconnect event which is fine
mj.on('disconnect', () => {
console.log('mj disconnect');
});

// And now you try to disconnect immediately which is done synchronously
// but how do you want to disconnect since you are still not connected ...
mj.disconnect();

您可以做的是在确保已连接后尝试断开连接:)

const mj = ioClient(`https://localhost:${socketPort}`);

mj.on('connect', () => {

// Subscribe to disconnect event once you know you are connected
mj.on('disconnect', () => {
console.log('mj disconnect');
});

// Now disconnect once you are connected
mj.disconnect();
});

关于javascript - 当客户端调用断开连接时,Socket.io 服务器未收到 'disconnect' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45991165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com