Search code examples
node.jssocketsnestjs

WebSocket Error: 'socket hang up' when connecting to NestJS WebSocketGateway


I try to run simple socket gateway on nest js according official docs https://docs.nestjs.com/websockets/gateways.

My Gateway code :

import { WebSocketGateway, SubscribeMessage, WebSocketServer, MessageBody } from '@nestjs/websockets';
import { Server } from 'socket.io';

@WebSocketGateway(30001)
export class AppGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('test')
  handleEvent(@MessageBody() data: string): string {
    return data;
  }
}

app module

import { Module } from '@nestjs/common';

import { AppService } from './app.service';
import { AppGateway } from './app.gateway';

@Module({
  imports: [],
  controllers: [],
  providers: [AppService, AppGateway],
})
export class AppModule { }

and main which tests itself

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as WebSocket from 'ws';


async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true, httpsOptions: { rejectUnauthorized: false } });
  await app.listen(3001);
}

function test() {
  const ws = new WebSocket('ws://localhost:30001');


  ws.onopen = function () {
    console.log('open WebSocket');


    ws.send(JSON.stringify({
      event: 'test',
      data: { message: 'Hello world!' }
    }));
  };

  ws.onmessage = function (event) {
    console.log('Server get messega:', event.data);
  };

  ws.onerror = function (error) {
    console.log('Error WebSocket:', error);
  };

  ws.onclose = function () {
    console.log('WebSocket closed');
  };
}

bootstrap();
test();

After run application i see following:

[Nest] 5916  - 23.09.2024, 13:38:42     LOG [NestFactory] Starting Nest application...
[Nest] 5916  - 23.09.2024, 13:38:42     LOG [InstanceLoader] AppModule dependencies initialized +11ms
[Nest] 5916  - 23.09.2024, 13:38:42     LOG [WebSocketsController] AppGateway subscribed to the "test" message +35ms
[Nest] 5916  - 23.09.2024, 13:38:42     LOG [NestApplication] Nest application successfully started +3ms
Error WebSocket: ErrorEvent {
  [Symbol(kTarget)]: WebSocket {
    _events: [Object: null prototype] {
      open: [Function],
      message: [Function],
      error: [Function],
      close: [Function]
    },
    _eventsCount: 4,
    _maxListeners: undefined,
    _binaryType: 'nodebuffer',
    _closeCode: 1006,
    _closeFrameReceived: false,
    _closeFrameSent: false,
    _closeMessage: <Buffer >,
    _closeTimer: null,
    _extensions: {},
    _paused: false,
    _protocol: '',
    _readyState: 2,
    _receiver: null,
    _sender: null,
    _socket: null,
    _bufferedAmount: 0,
    _isServer: false,
    _redirects: 0,
    _autoPong: true,
    _url: 'ws://localhost:30001/',
    _req: null,
    [Symbol(kCapture)]: false
  },
  [Symbol(kType)]: 'error',
  [Symbol(kError)]: Error: socket hang up
      at connResetException (node:internal/errors:683:14)
      at Socket.socketOnEnd (node:_http_client:471:23)
      at Socket.emit (node:events:377:35)
      at endReadableNT (node:internal/streams/readable:1312:12)
      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
    code: 'ECONNRESET'
  },
  [Symbol(kMessage)]: 'socket hang up'
}
WebSocket closed

Whats problem here?I tried another ports,cors etc.Also test socket from postman returns the same error - socket hang up

https://github.com/nestjs/nest/tree/master/sample/02-gateways

For that example server running log:

  [Nest] 1432  - 26.09.2024, 21:30:41     LOG [NestFactory] Starting Nest application...
    [Nest] 1432  - 26.09.2024, 21:30:41     LOG [InstanceLoader] AppModule dependencies initialized +21ms
    [Nest] 1432  - 26.09.2024, 21:30:41     LOG [InstanceLoader] EventsModule dependencies initialized +0ms
    [Nest] 1432  - 26.09.2024, 21:30:41     LOG [WebSocketsController] EventsGateway subscribed to the "events" message +62ms
    [Nest] 1432  - 26.09.2024, 21:30:41     LOG [WebSocketsController] EventsGateway subscribed to the "identity" message +0ms
    [Nest] 1432  - 26.09.2024, 21:30:41     LOG [NestApplication] Nest application successfully started +4ms
    Application is running on: http://[::1]:3000

And client browser console logs:

Connected
index.html:15 event 1
index.html:15 event 2
index.html:15 event 3
index.html:11 Identity: 0

Seems like all fine. But when i try to connect via wscat

PS C:\test_gateway\nest\sample\02-gateways> wscat -c ws://localhost:3000
error: socket hang up

Postman the same. enter image description here

The problem was the default socket adapter is IO.

https://docs.nestjs.com/websockets/adapter

After i used the ws adapter all works fine.

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.useWebSocketAdapter(new WsAdapter(app));**
  await app.listen(30001);
}

bootstrap();

Solution

  • the docs have example to test the socket, you should do like this, try it out