【问题标题】:Nest.js socket.io ping/pong between server/client服务器/客户端之间的 Nest.js socket.io ping/pong
【发布时间】:2019-10-19 05:07:31
【问题描述】:

我在socket.io中使用nestjs后端和Vuejs前端,需要查看用户是否“isAlive”。

我尝试 ping 服务器端和 pong 客户端,但服务器端什么都做...

服务器端(nest.js)

@WebSocketGateway({
  pingTimeout: 100
})
export class LockGateway {

  @SubscribeMessage('ping')
    ping(socket: Socket, data: any) {
      console.log(`Ping with ${data.toString()}`);
      socket.emit('pong', (response) => {
        console.log(`Response from client side : ${response.toString()}`);
      });
  }
}

客户端(vuejs/ts)

this.socket.on('pong', () => {
        console.log('PONG I m alive');
        this.socket.emit('ping', 'I m alive');
      });

在客户端,我在 pong 中拥有所有 console.log,但在服务器端,什么都没有:/

【问题讨论】:

  • 你有没有尝试增加ping超时,可能没有pong的时间超过100
  • pingTimeout 没有任何改变,我改变了策略,并使用addEventListener 和window.setTimeout(this.doInactive, this.timeoutInMiliseconds); 测试客户端不活动状态

标签: javascript typescript websocket socket.io nestjs


【解决方案1】:

您不能对SubscribeMessage 使用“ping”。尝试用另一个事件名称替换它。

【讨论】:

  • 欢迎您!您的回答可以使用更多信息。也许使用有效的事件名称添加示例代码 sn-p。或链接/文档引用为什么不能使用 ping。
【解决方案2】:

工作解决方案:

客户端:

this.socket.on('isAvailable', () => {
  this.socket.emit('keepAlive', socketClient.userUid);
});

服务器端:

@SubscribeMessage('join')
join(socket: Socket, data: any) {
if (data.userUid != null) {
  this.userUid = data.userUid;
}
if (data.userUid && data.userUid !== ANONYMOUS_USER) {
  this.keepAliveInterval = setInterval(() => {
    socket.emit('isAvailable');
  }, RETRY_EACH);
  this.setOfflineTimeout(socket, data.userUid);
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 2017-01-29
    • 2020-03-08
    • 2020-06-20
    • 2020-04-07
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多