1

I'm currently working on a NestJS application where I've implemented WebSocket functionality using the @nestjs/websockets | socket.io | @nestjs/platform-socket.io modules. However, I'm encountering difficulties establishing WebSocket connections.

I tried to connect both from the browser (developer console) and a small NodeJS app :

Connection from Chrome Developer Console

I'm using the command ws://localhost:3000 and getting the following error : VM44:1 WebSocket connection to 'ws://localhost:3000' failed.

Connection from NodeJS app with the following code :

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();

Giving the following error :

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'
}

Now this is my NestJS app config :

  1. Gateway for Websocket (imported in the providers[] of app.module) :
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. My main.ts file

 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);"

Versions

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

Despite following the recommended practices and checking for potential errors/misconfigurations, I'm unable to resolve the problem.

2 Answers 2

1

You're using socket.io on the server side, you need to use socket.io-client on the client side to make the connection to the "socket" server. Socket.io does end up implementing websockets, but connecting directly with ws is not as simply supported. You can read about some other approaches here

Sign up to request clarification or add additional context in comments.

Comments

1

I had a similar problem, I fixed it by running npm i @nestjs/platform-ws or yarn add @nestjs/platform-ws depending on the package manager you are using. then importing the WsAdapter from the package into your main.ts file like so:

// other imports
import { WsAdapter } from '@nestjs/platform-ws'; // <---


async function bootstrap() {
  // Other bootstrapping codes
  app.useWebSocketAdapter(new WsAdapter(app)); // <---
  await app.listen(3000);
}
bootstrap();

1 Comment

This is for ws not socket.io. But still may be useful some people happy to switch

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.