I have researched this topic online and have found nearly-similar questions to this – But, I need to know why in NestJS we have to use two packages to implement WebSocket communication.
The two packages are,
- @nestjs/websockets
- @nestjs/platform-socket.io
I understand that WebSocket is the protocol and Socket.IO is a library which has both server and client versions of it.
In the gateway file of NestJS when implementing a WebSocket connection, one has to write code similar to below.
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Server } from 'socket.io';
My questions,
-
What is the difference between
WebSocketServerandServerhere? -
Why do we import
Serverfromsocket.ioand not@nestjs/platform-socket.io? -
How do you describe the purpose of using each of these packages in a single sentence?
>Solution :
@nestjs/websockets is the base package that makes websocket integration possible in NestJS. @nestjs/platform-socket.io is the specific package for socket.io integration, rather than something like @nestjs/platform-ws which is for the ws package.
WebsocketServer is the decorator to tell Nest to inject the websocket server, Server is the socket.io type for the server.
We import Socket from socket.io because @nestjs/platform-socket.io is really just for the websocket adapter that plugs into Nest’s platform.
Single sentences:
@nestjs/websockets: allows for websocket communication via a websocket adapter@nestjs/platform-socket.io: socket.io websocket adapter to allow for socket.io websocket communication with the serversocket.io: a websocket implementation and engine that is usable with and without NestJS