Socket.io服务器没有收到'断开'客户端呼叫断开时的事件

时间:2017-08-31 22:55:34

标签: javascript node.js socket.io

我正在使用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', ...)侦听器?

1 个答案:

答案 0 :(得分:2)

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

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