0

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,

  1. What is the difference between WebSocketServer and Server here?

  2. Why do we import Server from socket.io and not @nestjs/platform-socket.io?

  3. How do you describe the purpose of using each of these packages in a single sentence?

1 Answer 1

7

@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 server
  • socket.io: a websocket implementation and engine that is usable with and without NestJS
1
  • I'm super thankful for this answer. Probably the fastest and one of the best answers I have received. This cleared a lot for me. Thanks @Jay!
    – RukshanJS
    Aug 12, 2022 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.