Socket.io 在 NestJS 中连接后客户端断开连接

Socket.io client is getting disconnected just after connection in NestJS

我正在尝试使用 nestjs 创建聊天,但它 @SubscribeMessage() 有问题, 连接实现工作正常,但是当我尝试监听来自前端的发射和 console nestjs 中的数据时,它不起作用

import { Server, Socket } from 'socket.io';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Repository } from 'typeorm';
import { Messenger } from './entities/messenger.entity';

@Injectable()
@WebSocketGateway(5000)
export class MessengerGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Messenger)
    private messageRepository: Repository<Messenger>,
  ) {}

  @SubscribeMessage('loadPeople')
  handleEvent(client: Socket, data){
    console.log(data);
    // this is not working
  }

  async afterInit(server: Server) {
    console.log('Init');
  }

  @SubscribeMessage('is-online')
  async handleConnection(client: Socket) {
    console.log('connected');
    // I can see this message in console
  }

  @SubscribeMessage('is-offline')
  async handleDisconnect(client: Socket) {
    console.log('disconnected');
     // I can see this message in console
  }
}

我从前端发送这个请求

import { io } from "socket.io-client";
const  ENDPOINT = "localhost:5000";
let socket

function App(){
  useEffect(()=>{
          socket = io(ENDPOINT)
          socket.emit('loadPeople', {token: localStorage.token})
  },[])

  return (
  //...
  )
}

当我将 nodejs(expressjs) 与 socket.io 一起使用时它有效, 但是当我尝试使用 nestjs 执行此操作时,它不起作用

基于NestJS Websocket documentation,NestJS socketIO 服务器仍然是 v2.

@nestjs/platform-socket.io currently depends on socket.io v2.3 and socket.io v3.0 client and server are not backward compatible. However, you can still implement a custom adapter to use socket.io v3.0. Please refer to this issue for further information.

如果您检查 version compatibility,您将看到 socketIO 服务器 v2 与 socketIO 客户端 v4 不兼容。

最简单的解决方案是在前端的 package.json 中使用 socket.io-client v2.3.0

或者,如果您想探索:socketIO 服务器 v3 与 socketIO 客户端 v4 兼容。因此,我相信您可以查看 this issue(如 NestJS 文档中所述)并尝试将您的 NestJS socketIO 服务器转换为支持 socketIO 客户端 v3。希望这也能支持 socketIO client v4。 (虽然我没有测试这个!)

希望对您有所帮助。干杯!!!