【问题标题】:Socket.io client is getting disconnected just after connection in NestJS在 NestJS 中连接后,Socket.io 客户端正在断开连接
【发布时间】:2021-07-22 22:28:29
【问题描述】:

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

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 执行此操作时,它不起作用

【问题讨论】:

  • 当你说你可以看到connected和disconnected时,是不是意味着你会立即看到一个接一个?
  • @Eranga Heshan,是的,我的意思是
  • 你的前端socket.io-client是什么版本?
  • @Eranga Heshan,我添加了连接和断开屏幕的问题,我的socket版本是4.0.1

标签: reactjs websocket socket.io nestjs nestjs-gateways


【解决方案1】:

基于NestJS Websocket documentation,NestJS socketIO 服务器仍处于 v2 中。

@nestjs/platform-socket.io 目前依赖于 socket.io v2.3 和 socket.io v3.0 客户端和服务器不向后兼容。但是,您仍然可以实现自定义适配器来使用 socket.io v3.0。请参阅此问题以获取更多信息。

如果你检查version compatibility,你会看到socketIO server v2和socketIO client v4不兼容。

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

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

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

【讨论】:

  • 非常感谢您的回答,它有效)
  • 很高兴我能帮上忙! ?
猜你喜欢
  • 2017-07-17
  • 1970-01-01
  • 2014-12-16
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 2015-07-28
相关资源
最近更新 更多