An Websocket Chat App
Tech Stack:
ws library, WsAdapter in main.ts
the gateway is here
I implemented the LifeCycle methods, followed the docs and when I log the socket.id in handleConnection method I get undefined everytime.
tried with client.handshake also, received undefined there too, however I could connect and transmit message through the postman
Please help, it's a bit urgency
import { Logger } from "@nestjs/common";
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
OnGatewayInit,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from "@nestjs/websockets";
import { Server } from "ws";
import { ChatService } from "src/chat/chat.service";
// import { Server, Socket } from "socket.io";
@WebSocketGateway({
cors: true,
transports: ["websocket"],
// namespace: "chat",
path: "chat",
allowUpgrades: true,
})
export class WebsocketGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer() server: Server;
private readonly logger = new Logger("WS");
constructor(private readonly chatService: ChatService) {}
afterInit(server: Server) {
this.logger.log("Websocket Initialized");
}
async handleConnection(client: any, ...args: any[]) {
this.logger.log("New Websocket Connection");
console.log("Socket ID: ", client.id); // undefined
console.log("Socket ID: ", client.handshake); // undefined
// await this.chatService.getUserFromSocket(socket);
}
handleDisconnect(client: any) {
this.logger.log("Client Disconnected");
}
@SubscribeMessage("send_message")
handleMessage(@MessageBody() data: string, @ConnectedSocket() socket: any): string {
console.log(socket.id);
this.logger.log(`Received: ${data}`);
return data.toUpperCase();
}
}