DEV Community

Cover image for How to Build a Real-Time Chat Application Using Socket.io
Hitendra Mali
Hitendra Mali

Posted on

How to Build a Real-Time Chat Application Using Socket.io

In this tutorial, I’ll walk you through the process of building a real-time chat application using Socket.io with Node.js and Express. This is a beginner-friendly guide that will give you a practical understanding of how real-time communication works in web applications. I’ll show you how to set up the server, create the front-end interface, and establish communication between the client and server using Socket.io.

What You'll Learn

  • What Socket.io is and how it works
  • Setting up a basic Node.js server
  • Integrating Socket.io for real-time communication
  • Building the front-end with HTML and JavaScript
  • Sending and receiving messages in real-time

Prerequisites

Before I start, make sure you have the following installed:

  • Node.js: You can download it from here.
  • npm (Node Package Manager): This comes bundled with Node.js, so if you have Node.js installed, you already have npm.
  • You should also have a basic understanding of JavaScript, HTML, and CSS.

Step 1: Set Up Your Project

Let’s begin by setting up a new project.

  • Create a new directory for your project and navigate into it:

mkdir real-time-chat
cd real-time-chat

  • Initialize a new Node.js project:

npm init -y

  • Install necessary dependencies: I’ll need Express for the server and Socket.io for real-time communication.

npm install express socket.io

Step 2: Set Up the Backend (Node.js & Express)

I’ll create a new file called server.js. This file will contain the backend code.

  • Create server.js and add the following code to set up a basic Express server with Socket.io:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

// Set up the app
const app = express();
const server = http.createServer(app);
const io = socketIo(server);  // Initialize Socket.io

// Serve static files (for front-end)
app.use(express.static('public'));

// Listen for incoming socket connections
io.on('connection', (socket) => {
    console.log('A user connected');

    // Listen for messages from clients
    socket.on('chat message', (msg) => {
        // Emit the message to all connected clients
        io.emit('chat message', msg);
    });

    // Handle disconnection
    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
});

// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • I use Express to serve static files (the front-end).
  • Socket.io is initialized and listens for incoming connections.
  • When a user sends a message via 'chat message', it’s broadcasted to all connected clients using io.emit().
  • When a user disconnects, the server logs a message.

Step 3: Set Up the Frontend (HTML & JavaScript)

Now, I’ll create a simple front-end where users can send and receive messages.

  • Create a folder named public in your project directory. This will hold your front-end files.
  • Inside the public folder, I’ll create an index.html file. This will be the chat interface.
<!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>
    <style>
        body { font-family: Arial, sans-serif; }
        ul { list-style-type: none; padding: 0; }
        li { padding: 8px; margin: 5px 0; background-color: #f1f1f1; }
        input[type="text"] { width: 300px; padding: 10px; margin: 10px 0; }
        button { padding: 10px; }
    </style>
</head>
<body>
    <h1>Real-Time Chat Application</h1>
    <ul id="messages"></ul>
    <form id="form">
        <input id="input" autocomplete="off" placeholder="Type a message" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        // Connect to the server
        const socket = io();

        // Get DOM elements
        const form = document.getElementById('form');
        const input = document.getElementById('input');
        const messages = document.getElementById('messages');

        // Send message on form submit
        form.addEventListener('submit', (e) => {
            e.preventDefault();  // Prevent page reload
            socket.emit('chat message', input.value);  // Emit message to server
            input.value = '';  // Clear input field
        });

        // Listen for incoming messages from the server
        socket.on('chat message', (msg) => {
            const li = document.createElement('li');
            li.textContent = msg;
            messages.appendChild(li);
        });
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The chat interface includes an input field to type messages and a button to send them.
  • I use Socket.io’s client library to establish a connection with the server.
  • When a message is sent, it’s emitted via the chat message event.
  • Incoming messages are displayed in the
      list element.

Step 4: Run the Application

Now that everything is set up, let's run the application.

  • Start the server:

node server.js

  • Open your browser and navigate to http://localhost:3000. You should see your chat interface.

  • Open the same URL in multiple tabs or different browsers to test real-time communication. When you send a message in one tab, it should appear in all other tabs in real-time.

Step 5: Conclusion

Congratulations! You’ve successfully built a real-time chat application using Socket.io. This application allows users to communicate with each other in real time, which is a powerful feature for many modern web applications. Now you can build on this by adding more features, such as user authentication, private messages, or chat rooms.

What’s Next?

  • Add user authentication to allow users to sign in before chatting.
  • Store chat messages in a database like MongoDB for persistence.
  • Enhance the UI with CSS frameworks like Bootstrap or Tailwind CSS.

Feel free to modify the project to suit your needs and explore other Socket.io features like rooms and namespaces!

Happy coding!

Top comments (0)