How to use web sockets in node js for real time communication - fincode fusion

How to Use WebSockets in Node.js: A Comprehensive Guide

In this post, I will guide you on how to use WebSockets in Node.js to create a real-time chat application.

What Are WebSockets?

A WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It is designed to enable interactive communication between a client (such as a web browser) and a server, allowing both parties to send and receive data simultaneously. Unlike HTTP, which is a request-response protocol, WebSocket allows for persistent connections where the server can send data to the client without the client explicitly requesting it each time.

Key Features and Characteristics of WebSocket

  • Full-Duplex Communication: Both the client and server can send and receive messages independently and simultaneously. This makes it suitable for real-time applications like chat apps, live updates, and multiplayer games.
  • Persistent Connection: Once a WebSocket connection is established, it remains open until either the client or server decides to close it. This reduces the overhead associated with repeatedly opening and closing connections, as seen in traditional HTTP requests.
  • Low Latency: WebSockets are designed to minimize latency, making them ideal for applications where real-time data transfer is critical.
  • Event-Driven Communication: WebSocket communication is typically event-driven, meaning the client and server can respond to events (like receiving a message) immediately as they occur.
  • Protocol Upgrade: The WebSocket protocol starts with an HTTP handshake to establish the connection, then upgrades the connection to a WebSocket connection. This allows WebSockets to work seamlessly with existing HTTP infrastructures.
  • Binary and Text Data: WebSocket supports the transmission of both text and binary data, making it versatile for various types of applications.

Example Use Cases

  • Real-Time Chat Applications: Enables instant messaging between users.
  • Live Data Feeds: Financial tickers, live sports scores, or social media updates.
  • Online Gaming: Facilitates real-time interaction between players.
  • Collaborative Tools: Real-time collaboration on documents, whiteboards, or coding platforms.
  • IoT Devices: Real-time monitoring and control of Internet of Things devices.

Implementing WebSockets in Node.js

Step 1: Set Up the Project


mkdir chat-app
cd chat-app
npm init -y
    

Step 2: Install Dependencies


npm install express socket.io
    

Step 3: Create the Server

Create a file named server.js and add the following code:


const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

app.use(express.static('public'));

io.on('connection', (socket) => {
    console.log('A user connected');

    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
    

Step 4: Create the Client

Create a directory named public and inside it, create an index.html file with the following content:


<!DOCTYPE html>
<html>
<head>
    <title>Chat App</title>
</head>
<body>
    <ul id="messages"></ul>
    <form id="form" action="">
        <input id="input" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io();
        const form = document.getElementById('form');
        const input = document.getElementById('input');
        const messages = document.getElementById('messages');

        form.addEventListener('submit', function(event) {
            event.preventDefault();
            if (input.value) {
                socket.emit('chat message', input.value);
                input.value = '';
            }
        });

        socket.on('chat message', function(msg) {
            const item = document.createElement('li');
            item.textContent = msg;
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });
    </script>
</body>
</html>
    

Step 5: Run the Application

Start the server by running the following command:


node server.js
    

Open your web browser and navigate to http://localhost:3000 to see your chat application in action. Open multiple browser tabs to simulate multiple users and start chatting.

Need Help Implementing Your Real-Time Chatting App?

You can contact us on WhatsApp or email us at ahmedaliranafiv@gmail.com.

0 Comments