,

Real Time Messaging with Socket.IO in NodeJS using WebSockets

Posted by


WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It allows for real-time, bi-directional communication between a server and clients. In this tutorial, we will be using Node.js and Socket.IO to implement WebSocket in a Node.js application for real-time messaging.

Prerequisites

Before we get started, make sure you have Node.js and npm installed on your system.

Installing Socket.IO

Socket.IO is a JavaScript library that enables real-time, bidirectional and event-based communication. To install Socket.IO, run the following command in your terminal:

npm install socket.io

Creating a WebSocket Server

To create a WebSocket server in Node.js using Socket.IO, follow these steps:

  1. Create a new Node.js project by running the following command in your terminal:

    mkdir websocket-example
    cd websocket-example
    npm init -y
  2. Create a new JavaScript file, server.js, and open it in your code editor.

  3. Import the required modules at the beginning of your server.js file:

    const express = require('express');
    const http = require('http');
    const socketIo = require('socket.io');
  4. Create an Express app and a HTTP server:

    const app = express();
    const server = http.createServer(app);
  5. Create a Socket.IO server and attach it to the HTTP server:

    const io = socketIo(server);
  6. Now, you can listen to connection events and handle messages in your Socket.IO server:

    io.on('connection', (socket) => {
    console.log('A user connected');
    
    socket.on('message', (data) => {
    console.log('Message received:', data);
    
    // Broadcast the message to all connected clients
    io.emit('message', data);
    });
    
    socket.on('disconnect', () => {
    console.log('A user disconnected');
    });
    });
  7. Start the server and listen on a port (e.g., 3000):
    
    const PORT = 3000;

server.listen(PORT, () => {
console.log(Server running on port ${PORT});
});


### Creating a WebSocket Client
To create a WebSocket client in Node.js using Socket.IO, follow these steps:

1. Create a new JavaScript file, `client.js`, and open it in your code editor.

2. Import the required modules and connect to the WebSocket server:
```javascript
const io = require('socket.io-client');
const socket = io('http://localhost:3000');
  1. Listen to the message event and send messages to the server:
    
    socket.on('message', (data) => {
    console.log('Message received:', data);
    });

// Send a message to the server
socket.emit(‘message’, ‘Hello, world!’);


4. Run the client script using Node.js:
```bash
node client.js

Testing the WebSocket Connection

To test the WebSocket connection, open multiple instances of the client.js script in separate terminal windows. You should see the messages being sent and received in real-time between the clients.

Conclusion

In this tutorial, we covered how to create a WebSocket server and client using Node.js and Socket.IO for real-time messaging. WebSocket enables bi-directional communication between a server and clients, allowing for real-time updates and interactions in web applications. Socket.IO simplifies the implementation of WebSocket by providing a high-level API and handling the underlying WebSocket protocol details. Try experimenting with different events and message formats to build more complex real-time applications using WebSocket in Node.js.

0 0 votes
Article Rating
44 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@hamudxd9497
2 months ago

SALUTE TO YOU SIR ❤

@syedaimtiyaz8842
2 months ago

Wow .. Thank you for this clear explanation

@AnishaGaur-bf1uk
2 months ago

Thanku u for such a great help 🎉

@Gamer_with_knowledge
2 months ago

This guy will close the shops of all paid NODE Js course influencers 🙂
Thank you so much Piyush for the efforts

@samiranroyy1700
2 months ago

sir🥰

@debjitkunduscience11a93
2 months ago

First back-end project that I understood completely…like I have implemented some by debugging using chat gpt ..but this was something else

@ravijha4965
2 months ago

How many websocket connection we can have ? What does it depend on

@CptSnunu-ii4um
2 months ago

Do you mix indian and english? cause sometimes i dont understand

@shahharsh8433
2 months ago

Company mee freshers kee paas kyaa karate hee any idea in node, express ?

@daakumangalsingh235
2 months ago

Checking ki yt ke comments me websocket laga hai ya nahi😂

@dkisback6072
2 months ago

done it first day

@User-yb3yc
2 months ago

Next level Explanation . Thank You sir

@tier3_coder
2 months ago

very informative video

@studyplans3783
2 months ago

bahii itna acha kyo pdha te ho

@shahebazkhanpathan2926
2 months ago

Thank you. Very much easy explanation!

@kritikajoshi8291
2 months ago

bhai i was struggling so much with websockets during my internship, my college taking lakhs of fees didn't touch this topic and you taught this so well, THANKYOU

@muhammad_haseeb_pk
2 months ago

I am still sorry for those who has not yet discovered his channel it is a milestone I dont have any words to explain how grateful I am that I find this, Alhumdullilah

@CodeDynamo
2 months ago

Zabardast explanation, awesome ❤

@pritimohan2298
2 months ago

Email verification via OTP iske upar ek video banaa dijiye please

@saibhaskar6939
2 months ago

Bro your explanation is awesome. Can you keep English subtitles . Because people who don't Hindi it's difficult to them , I'm also one of person in it.

Thank you