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 :
- 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}`);
}
}
- 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.