I’m trying to setup a websocket in my nestjs application. env and package versions are the as the following:
Node: v18.17.0
@nestjs/core: "^9.0.0"
@nestjs/platform-socket.io: "^10.3.8"
And I have create multiple files to implement:
chat.gateway.ts:
import {
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
OnGatewayInit,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Logger, OnModuleInit } from '@nestjs/common';
import { Server, Socket } from 'socket.io';
@WebSocketGateway(4040)
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect, OnModuleInit {
@WebSocketServer() server: Server;
private logger: Logger = new Logger('ChatGateway');
onModuleInit() {
this.logger.log('ChatGateway Module has been initialized');
}
@SubscribeMessage('newMessage')
handleMessage(@MessageBody() body: any): void {
this.logger.log(`Message received: ${JSON.stringify(body)}`);
this.server.emit('message', body);
}
afterInit(server: Server): void {
console.log('WebSocket server initialized');
}
handleConnection(client: Socket, ...args: any[]): void {
this.logger.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket): void {
this.logger.log(`Client disconnected: ${client.id}`);
}
}
chat.gateway.module.ts:
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';
@Module({
providers: [ChatGateway],
})
export class ChatGatewayModule {}
app.module.ts:
@Module({
imports: [
...otherModules,
ChatGatewayModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
constructor(private readonly logger: LoggerService) {
mongoose.set('debug', (collectionName: any, method: any, query: any, doc: any) => {
logger.info(`Mongoose: ${collectionName}.${method}(${JSON.stringify(query)}, ${JSON.stringify(doc)})`);
});
this.logger.log("App is running...");
}
private onApplicationShutdown(signal: string) {
this.logger.log("App is shutting down...");
}
}
And I have create a simple HTML file to check the connection:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<script>
const socket = new WebSocket('ws://localhost:4040/chat');
socket.onopen = function(event) {
console.log('WebSocket connection established');
socket.send(JSON.stringify({ message: 'Hello Server!' }));
};
socket.onmessage = function(event) {
console.log('Message from server:', event.data);
};
socket.onclose = function(event) {
console.log('WebSocket connection closed');
};
socket.onerror = function(error) {
console.error('WebSocket error:', error);
};
</script>
</body>
</html>
I’m running the nestjs app by running npm run start:dev
on my local. It prints LOG [ChatGateway] ChatGateway Module has been initialized
, but doesn’t print WebSocket server initialized
which is in the afterInit
method.
Then I tried the connection on the HTML page by using Google Chrome, it fails with WebSocket connection to 'ws://localhost:4040/chat' failed:
message.
What should I do to fix?
Thanks.