我正在尝试与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执行此操作时,它不起作用