gpt4 book ai didi

javascript - 为什么 'new WebSocket()' 对 nestjs 不起作用?

转载 作者:行者123 更新时间:2023-12-05 02:42:31 26 4
gpt4 key购买 nike

我正在发送 const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world'); 来自客户端,我在服务器上收到日志“已连接”日志,但不是“hello world”。 socket.send() 不适用于 NestJS。当我查看 chrome 网络时。它发送数据但不在服务器中接收。这是代码:chat.gateway.ts

@WebSocketGateway()
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
handleConnection(client: any, ...args: any[]): any {
console.log('connected');
}

handleDisconnect(client: any): any {
console.log(client);
console.log('disconnected');
}

@SubscribeMessage('message')
handleEvent(client: any, data: any): WsResponse<any> {
const event = 'events';
return { event, data };
}

afterInit(server: any): any {
console.log(server.path);
}
}

ma​​in.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from '@nestjs/platform-ws';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: 'http://localhost:4200',
credentials: true,
});
app.useWebSocketAdapter(new WsAdapter(app));
await app.listen(3000);
}

bootstrap();

最佳答案

查看 Github 示例:https://github.com/nestjs/nest/tree/master/sample/16-gateways-ws

在客户端:

const socket = new WebSocket('ws://localhost:80');
socket.onopen = () => {
console.log('Connected');
socket.send(
JSON.stringify({
event: 'message',
data: 'my very important message',
}),
);
socket.onmessage = (data) => {
console.log(data);
};
};

这应该可以解决问题

关于javascript - 为什么 'new WebSocket()' 对 nestjs 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67587213/

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