Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between @nestjs/websockets and @nestjs/platform-socket.io packages in NestJS

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>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 server
  • socket.io: a websocket implementation and engine that is usable with and without NestJS
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading