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

2q5ifsrm  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(248)

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

从Chrome开发者控制台连接

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

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

const WebSocket = require('ws');

const serverAddress = 'ws://localhost:3000';

let client;

function createWebSocket() {
  client = new WebSocket(serverAddress);

  client.on('open', () => {
    console.log('WebSocket connection opened');
  });

  client.on('message', (message) => {
    console.log('Received message:', message);
  });
}

createWebSocket();

字符串
给出以下错误:

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

这是我的NestJS应用配置:

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

import {
  WebSocketGateway,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ transports: ['websocket'] })
export class KoliWebSocketGateway
  implements OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer() server: Server;

  handleConnection(client: Socket) {
    console.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }
}


1.我的main.ts文件

const app = await NestFactory.create(AppModule, new ExpressAdapter(server));

  app.useWebSocketAdapter(new IoAdapter(app));

  app.setGlobalPrefix('api/v1');
  app.enableCors({
    preflightContinue: false,
  });

  const swaggerConfig = new DocumentBuilder()
    .setTitle('Koli API Reference')
    .setDescription('REST API for Koli app.')
    .setVersion('1.0.0')
    .build();

  const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);

  SwaggerModule.setup('reference', app, swaggerDocument);

  await app.listen(3000);"

版本号

Ubuntu 20.04
Node.js v20.9.0
@nestjs/common: ^10.2.8
@nestjs/config: ^3.1.1
@nestjs/core": ^10.2.8
@nestjs/platform-express: ^10.2.8
@nestjs/platform-socket.io: ^10.2.8
@nestjs/websockets: ^10.2.8
socket.io: ^4.7.2
@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

相关问题