gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:25:21 24 4
gpt4 key购买 nike

我正在尝试使用 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
}
}
enter image description here

我从前端发送这个请求

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。 (虽然我没有测试这个!)

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

关于reactjs - 在 NestJS 中连接后,Socket.io 客户端断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67319314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com