我想通过 NestJs 使用 websockets。根据我创建的文档:
// events.gateway.ts
import {
MessageBody,
OnGatewayInit,
SubscribeMessage,
WebSocketGateway
} from "@nestjs/websockets";
@WebSocketGateway(81, { transports: ['websocket'] })
export class EventsGateway implements OnGatewayInit {
@SubscribeMessage('events')
handleEvent(@MessageBody() data: string): string {
console.log(data, 'socket')
return data;
}
afterInit(server: any): any {
console.log('init')
}
}
之后,我将上面的代码连接到我的module;
@Module({
providers:[TestService, EventsGateway], // connect EventsGateway
controllers:[TestController],
})
export class TestModule {
}
现在,使用 react js 我尝试从 ui 发送消息:
import React, {} from 'react';
import './App.css';
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:81/test";
function App() {
const socket = socketIOClient(ENDPOINT, {
transports: ['websocket']
});
function sendEmail(e: any) {
e.preventDefault();
socket.emit('events', {
name: 'Nest'
});
}
return (...);
}
export default App;
问题:现在当我触发时socket.emit(),代码不起作用并且我在服务器上没有得到任何东西,为什么以及如何使代码可用?