Building a Basic Chat Application with WebSocket and Socket.IO

Rahul BoneyRahul Boney
2 min read

WebSockets provide a way to open a persistent connection between the client and the server, allowing real-time communication with minimal overhead. In this article, I'll walk you through building a simple chat application using WebSocket via Socket.IO.

Setting Up the Project

First, create a new directory for your project and navigate into it:

mkdir websocket-chat
cd websocket-chat

Initialize a new Node.js project and install the necessary dependencies:

npm init -y
npm install express socket.io

Creating the Server

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

const http = require('http');
const express = require('express');
const path = require('path');
const { Server } = require("socket.io");

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

io.on("connection", (socket) => {
    console.log("A new user has connected", socket.id);

    socket.on("user-message", (message) => {
        console.log("Received message from client:", message);
        io.emit("message", message);
    });
});

app.use(express.static(path.resolve('./public')));

app.get('/', (req, res) => {
    res.sendFile(path.resolve('./public/index.html'));
});

server.listen(9000, () => console.log(`Server started on PORT: 9000`));

Creating the Client

Create a public directory, and inside it, create an index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat App</title>
</head>
<body>
    <h1>Chatting</h1>
    <input type="text" id="message" placeholder="Enter message"/>
    <button id="sendBtn">Send</button>
    <div id="messages"></div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io();
        const sendBtn = document.getElementById('sendBtn');
        const messageInput = document.getElementById('message');
        const allMessages = document.getElementById('messages');

        socket.on("connect", () => {
            console.log('Connected to server');
        });

        socket.on("message", (message) => {
            console.log('Received message from server:', message);
            const p = document.createElement('p');
            p.innerText = message;
            allMessages.appendChild(p);
        });

        sendBtn.addEventListener('click', () => {
            const message = messageInput.value;
            console.log('Sending message:', message);
            socket.emit('user-message', message);
            messageInput.value = '';  
        });
    </script>
</body>
</html>

Running the Application

To start the server, run the following command:

node server.js

Open your browser and navigate to http://localhost:9000. You should see your chat application. Open multiple tabs to test real-time communication between clients.

Conclusion

You've now built a basic chat application using WebSocket and Socket.IO. This example demonstrates how easy it is to set up real-time communication in your web applications. You can find the complete source code in my GitHub repository. Feel free to clone it and experiment with adding more features.

Happy coding!

0
Subscribe to my newsletter

Read articles from Rahul Boney directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rahul Boney
Rahul Boney

Hey, I'm Rahul Boney, really into Computer Science and Engineering. I love working on backend development, exploring machine learning, and diving into AI. I am always excited about learning and building new things.