DeveloperBreeze

In this tutorial, we will create a real-time chat application using Node.js and WebSockets. Real-time communication is a crucial aspect of modern web applications, allowing users to interact with each other instantaneously. By leveraging WebSockets, we can establish a persistent connection between the client and server, enabling seamless data exchange.

Introduction to WebSockets

WebSockets provide a full-duplex communication channel over a single TCP connection, allowing both the client and server to send messages at any time. Unlike HTTP, WebSockets maintain a persistent connection, making them ideal for applications requiring real-time updates, such as chat apps, online gaming, and live notifications.

Setting Up the Node.js Environment

Step 1: Install Node.js

If you haven’t already installed Node.js, you can download it from the official website. Node.js includes npm, the package manager we will use to install dependencies.

Step 2: Create a Project Directory

mkdir websocket_chat
cd websocket_chat

Step 3: Initialize a Node.js Project

npm init -y

Step 4: Install Required Packages

npm install express socket.io

Building the Chat Application

Step 1: Create the Server

Create a file named server.js in your project directory and add the following:

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('chatMessage', (msg) => {
        io.emit('chatMessage', msg);
    });

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

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

Step 2: Create the Client

Create public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-Time Chat</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="chat-container">
        <ul id="messages"></ul>
        <form id="chat-form">
            <input id="message" autocomplete="off" placeholder="Type a message" />
            <button type="submit">Send</button>
        </form>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script src="main.js"></script>
</body>
</html>

Create public/styles.css

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.chat-container {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
}

#messages {
    list-style-type: none;
    padding: 0;
    max-height: 300px;
    overflow-y: auto;
    margin-bottom: 10px;
}

#messages li {
    padding: 8px;
    background-color: #f1f1f1;
    border-radius: 3px;
    margin-bottom: 5px;
}

#chat-form {
    display: flex;
}

#message {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 3px;
    margin-right: 5px;
}

button {
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 3px;
    padding: 8px 12px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

Create public/main.js

const socket = io();

const messageForm = document.getElementById('chat-form');
const messageInput = document.getElementById('message');
const messagesList = document.getElementById('messages');

messageForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const message = messageInput.value;
    socket.emit('chatMessage', message);
    messageInput.value = '';
});

socket.on('chatMessage', (message) => {
    const li = document.createElement('li');
    li.textContent = message;
    messagesList.appendChild(li);
});

Running the Application

  1. Start the Node.js server:
node server.js
  1. Open your browser and go to:

http://localhost:3000/

  1. Open multiple tabs or browsers to test real-time messaging.

Conclusion

In this tutorial, we built a real-time chat application using Node.js and WebSockets. We used Socket.io to establish a persistent connection between the client and server, allowing for real-time message exchange. This foundational knowledge can be extended to build more complex applications that require real-time communication, such as collaborative tools, online gaming, and live updates.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Build a Custom Rate Limiter in Node.js with Redis

// redisClient.js
const redis = require("redis");

const client = redis.createClient({ url: process.env.REDIS_URL });

client.on("error", (err) => console.error("Redis error:", err));
client.connect();

module.exports = client;
// rateLimiter.js
const client = require("./redisClient");

const rateLimiter = (limit = 100, windowSec = 3600) => {
  return async (req, res, next) => {
    const ip = req.ip;
    const key = `rate_limit:${ip}`;

    const current = await client.get(key);

    if (current !== null && parseInt(current) >= limit) {
      return res.status(429).json({ error: "Too many requests. Try later." });
    }

    const multi = client.multi();
    multi.incr(key);
    if (!current) {
      multi.expire(key, windowSec);
    }
    await multi.exec();

    next();
  };
};

module.exports = rateLimiter;

Apr 04, 2025
Read More
Tutorial
php

Building a Laravel Application with Vue.js for Dynamic Interfaces

Visit your application in the browser (e.g., http://127.0.0.1:8000) to see your Vue component in action.

Add a new route in routes/api.php:

Nov 16, 2024
Read More
Tutorial
json bash

Building Progressive Web Apps (PWAs) with Modern APIs

Note: Actual push functionality requires a server-side setup using libraries like web-push in Node.js.

PWAs can leverage various modern web APIs to enhance functionality. Here are a few examples:

Aug 05, 2024
Read More
AI Chat 1
Tailwind Component

AI Chat 1

No preview available for this content.

Jan 26, 2024
Read More
Code
php

JWT Token Creation and Verification in Node.js using 'jsonwebtoken'

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Simple HTTP Server in Node.js

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Read and Write Files in Node.js using 'fs' module

// Import 'fs' module
const fs = require('fs');

// Read a file
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Write to a file
fs.writeFile('newfile.txt', 'Hello, Node.js!', (err) => {
  if (err) throw err;
  console.log('File written successfully.');
});

Jan 26, 2024
Read More
Code
javascript

Simple RESTful API in Node.js using Express

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Date Manipulation and Sum Calculation

// Import required modules
const moment = require('moment');
const _ = require('lodash');

// Get the current date and time using Moment.js
const now = moment();

// Example array of numbers
const numbers = [1, 2, 3, 4, 5];

// Calculate the sum of the array using Lodash
const sum = _.sum(numbers);

Jan 26, 2024
Read More
Code
javascript

Access Command-line Arguments

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Set and Access Environment Variable

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Event Emitter using 'events' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Construct File Path using 'path' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Basic Authentication using 'express-basic-auth' middleware

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Create and Print Buffer

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Hashing Password with SHA-256 using 'crypto' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Parse URL and Query Parameters

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Execute Shell Command using 'child_process' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

File Stream Copy using 'fs' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Simple WebSocket Server using 'ws' library

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!