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:
-
Create a new Node.js project by running the following command in your terminal:
mkdir websocket-example cd websocket-example npm init -y
-
Create a new JavaScript file,
server.js
, and open it in your code editor. -
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');
-
Create an Express app and a HTTP server:
const app = express(); const server = http.createServer(app);
-
Create a Socket.IO server and attach it to the HTTP server:
const io = socketIo(server);
-
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'); }); });
- 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');
- 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.
SALUTE TO YOU SIR ❤
Wow .. Thank you for this clear explanation
Thanku u for such a great help 🎉
This guy will close the shops of all paid NODE Js course influencers 🙂
Thank you so much Piyush for the efforts
sir🥰
First back-end project that I understood completely…like I have implemented some by debugging using chat gpt ..but this was something else
How many websocket connection we can have ? What does it depend on
Do you mix indian and english? cause sometimes i dont understand
Company mee freshers kee paas kyaa karate hee any idea in node, express ?
Checking ki yt ke comments me websocket laga hai ya nahi😂
done it first day
Next level Explanation . Thank You sir
very informative video
bahii itna acha kyo pdha te ho
Thank you. Very much easy explanation!
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
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
Zabardast explanation, awesome ❤
Email verification via OTP iske upar ek video banaa dijiye please
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