Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7639

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T05:43:06+00:00 2024-11-28T05:43:06+00:00

Create your first WebSockets-based application in NestJS

  • 60k

Introduction

What are Websockets

Websockets is a communication protocol which provides full-duplex communication channels over a single TCP connection established between a web browser and a web server. This allows the server to sent to the browser without being called by the client. There are many usages of Websockets, like chat app, or account balance,… Where everything needs to be update in real time

Websockets in NestJS

According to NestJS, a gateway is simply a class annotated with @WebSocketGateway() decorator. Technically, gateways are platform-agnostic which makes them compatible with any WebSockets library once an adapter is created.

Before we dive in writing the application, I assume you already know how to create a NestJS application with TypeORM implemented, if not, you can check out my tutorial right here

Set up

We are going to build a simple send and receive message app

First, we need to install some dependencies

yarn add socket.io @nestjs/websockets @nestjs/platform-socket.io 
Enter fullscreen mode Exit fullscreen mode

Then we will create a Gateway called MessageGateway

export class MessageGateway   implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {  } 
Enter fullscreen mode Exit fullscreen mode

Don’t forget to add it to our providers in MessageModule

@Module({   imports: [TypeOrmModule.forFeature([Message])],   controllers: [MessagesController],   providers: [MessagesService, MessageGateway], }) export class MessagesModule {} 
Enter fullscreen mode Exit fullscreen mode

Build the Server

Right now the IDE will tell you that you need to have some methods called afterInit handleDisconnect handleConnection in MessageGateway

Because this is just a simple app, and we don’t actually need to do anything in these methods, we will simply log the data out

  private logger: Logger = new Logger('MessageGateway');    @WebSocketServer() wss: Server;    afterInit(server: Server) {     this.logger.log('Initialized');   }    handleDisconnect(client: Socket) {     this.logger.log(`Client Disconnected: ${client.id}`);   }    handleConnection(client: Socket, ...args: any[]) {     this.logger.log(`Client Connected: ${client.id}`);   } 
Enter fullscreen mode Exit fullscreen mode

With this, we will know when the Server started, which client is connected and disconnected

Handle events

We need 2 events in this app, first is the sendMessage event and the second is receiveMessage event

@SubscribeMessage('sendMessage')   async handleSendMessage(client: Socket, payload: string): Promise<void> {     const newMessage = await this.messagesService.createMessage(payload);     this.wss.emit('receiveMessage', newMessage);   } 
Enter fullscreen mode Exit fullscreen mode

With this piece of code, we will use SubscribeMessagedecorate to subscribe to the sendMessage event. Whenever a sendMessage event occured, we will create a new message through messageService .

Then we emit this created message through receiveMessage event

Build the Client

To test the gateway, we need a client, I will use the most popular UI library out there to test it, React

We need to install socket.io since the server uses socket.io

yarn add socket.io-client 
Enter fullscreen mode Exit fullscreen mode

Next we will create a socket with it

import io from "socket.io-client"; const socket = io("http://localhost:3000"); 
Enter fullscreen mode Exit fullscreen mode

Then we will implement the socket:

  useEffect(() => {     socket.on("receiveMessage", (msg) => {       receiveMessage(msg);     });      getInitialMessages();   }, []);    function getInitialMessages() {     fetch("http://localhost:3000/messages")       .then((res) => res.json())       .then((data) => {         setMessages(data);       });   }    function receiveMessage(msg: Message) {     const newMessages = [...messages, msg];     setMessages(newMessages);   }    function sendMessage() {     socket.emit("sendMessage", newMessage);     setNewMessage("");   } 
Enter fullscreen mode Exit fullscreen mode

You can see that on first render, I will subscribe to the receiveMessage event, to listen if there is any new event and take action with receiveMessage method. Then I get the initial messages through the get api

On receiveMessage method, I append new message to the state.

Every time we need to send a new message, we will emit sendMessage event

This will be the result:

Image description

Conclusion

This is the most basic example on how to create your first websockets app. You will know how to send and receive messages through the gateway. If the article is not that clear to you, just check out the source code

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

backendjavascriptnodewebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.