NestJS WebSocket连接问题:无法建立连接或接收数据

2q5ifsrm  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(344)

我目前正在开发一个NestJS应用程序,我已经使用**@nestjs/websockets实现了WebSocket功能|socket.io|@nestjs/platform-socket.io**模块。但是,我在建立WebSocket连接时遇到了困难。
我尝试从浏览器(开发者控制台)和一个小的NodeJS应用程序连接:

从Chrome开发者控制台连接

我正在使用命令ws://localhost:3000并得到以下错误:VM 44:1 WebSocket连接到“ws://localhost:3000”失败

使用以下代码从NodeJS应用程序连接:

  1. const WebSocket = require('ws');
  2. const serverAddress = 'ws://localhost:3000';
  3. let client;
  4. function createWebSocket() {
  5. client = new WebSocket(serverAddress);
  6. client.on('open', () => {
  7. console.log('WebSocket connection opened');
  8. });
  9. client.on('message', (message) => {
  10. console.log('Received message:', message);
  11. });
  12. }
  13. createWebSocket();

字符串
给出以下错误:

  1. WebSocket connection closed
  2. WebSocket error: Error: socket hang up
  3. at connResetException (node:internal/errors:721:14)
  4. at Socket.socketOnEnd (node:_http_client:519:23)
  5. at Socket.emit (node:events:526:35)
  6. at endReadableNT (node:internal/streams/readable:1408:12)
  7. at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  8. code: 'ECONNRESET'
  9. }

这是我的NestJS应用配置:

1.用于WebSocket的网关 (在app.module的providers[]中导入)

  1. import {
  2. WebSocketGateway,
  3. WebSocketServer,
  4. OnGatewayConnection,
  5. OnGatewayDisconnect,
  6. } from '@nestjs/websockets';
  7. import { Server, Socket } from 'socket.io';
  8. @WebSocketGateway({ transports: ['websocket'] })
  9. export class KoliWebSocketGateway
  10. implements OnGatewayConnection, OnGatewayDisconnect
  11. {
  12. @WebSocketServer() server: Server;
  13. handleConnection(client: Socket) {
  14. console.log(`Client connected: ${client.id}`);
  15. }
  16. handleDisconnect(client: Socket) {
  17. console.log(`Client disconnected: ${client.id}`);
  18. }
  19. }


1.我的main.ts文件

  1. const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
  2. app.useWebSocketAdapter(new IoAdapter(app));
  3. app.setGlobalPrefix('api/v1');
  4. app.enableCors({
  5. preflightContinue: false,
  6. });
  7. const swaggerConfig = new DocumentBuilder()
  8. .setTitle('Koli API Reference')
  9. .setDescription('REST API for Koli app.')
  10. .setVersion('1.0.0')
  11. .build();
  12. const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
  13. SwaggerModule.setup('reference', app, swaggerDocument);
  14. await app.listen(3000);"

版本号

  1. Ubuntu 20.04
  2. Node.js v20.9.0
  3. @nestjs/common: ^10.2.8
  4. @nestjs/config: ^3.1.1
  5. @nestjs/core": ^10.2.8
  6. @nestjs/platform-express: ^10.2.8
  7. @nestjs/platform-socket.io: ^10.2.8
  8. @nestjs/websockets: ^10.2.8
  9. socket.io: ^4.7.2
  10. @nestjs/cli: ^10.2.1


尽管遵循了建议的做法并检查了潜在的错误/错误配置,但我无法解决这个问题。

qfe3c7zg

qfe3c7zg1#

您在服务器端使用socket.io,您需要在客户端使用socket.io-client来连接到“socket”服务器。 Socket.io最终实现了websockets,但不支持直接使用ws连接。You can read about some other approaches here

相关问题