【问题标题】:Socket.io server not receiving 'disconnect' event when client calls disconnect客户端调用断开连接时,Socket.io 服务器未收到“断开连接”事件
【发布时间】:2018-02-09 23:35:49
【问题描述】:

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

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', ...)监听器?

【问题讨论】:

  • 您是否尝试过与客户端和服务器建立任何其他连接?他们有交流吗?尝试发出一个测试socket.emit('test', true) 然后看看你是否收到它
  • @serendipity 是的。

标签: javascript node.js socket.io


【解决方案1】:

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

// 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();
});

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多