# Building a Real-Time Chat Application with Socket.io

## **Introduction**

[Real-time](https://bytescrum.com/) chat [applications](https://www.geeksforgeeks.org/how-to-create-a-chat-app-using-socket-io-node-js/) have become increasingly popular for instant communication and user collaboration. In this guide, we will explore building a <mark>real-time chat application</mark> using [Socket.io](http://Socket.io), a JavaScript library that enables real-time, bidirectional and event-based communication between clients and servers.

### **1\. Setting Up Your Project**

* **Install Socket.io**: Start by creating a new Node.js project and installing [Socket.io](https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8) and [Express](https://expressjs.com/):
    

```bash
npm init -y
npm install express
npm install socket.io
```

* **Create Your Server**: Set up a basic Node.js server using Express and [Socket.io](https://medium.com/@abbasashraff12313/creating-a-real-time-chat-application-with-socket-io-and-react-ecca78c13819):
    

```javascript
// server.js
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);

server.listen(3000, () => {
    console.log('Server running on port 3000');
});
```

---

### **2\. Creating the Chat Interface**

* **Set Up Your Frontend**: Create an HTML file (index.html) for your chat interface:
    

```xml
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Chat Application</title>
</head>
<body>
    <div id="messages"></div>
    <input id="messageInput" type="text" placeholder="Enter your message">
    <button id="sendButton">Send</button>
</body>
</html>
```

* **Client-Side Socket.io Setup**: Include [Socket.io](https://dev.to/novu/building-a-chat-app-with-socketio-and-react-2edj) on the client side and connect to the server:
    

```xml
<!-- index.html -->
<script src="/socket.io/socket.io.js"></script>
<script>
    const socket = io();

    socket.on('connect', () => {
        console.log('Connected to server');
    });
</script>
```

---

### **3\. Handling Chat Events**

* **Sending Messages**: Handle sending messages from the client to the server:
    

```javascript
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');

sendButton.addEventListener('click', () => {
    const message = messageInput.value;
    socket.emit('chatMessage', message);
    messageInput.value = '';
});
```

* **Receiving Messages**: Handle receiving messages from the server and displaying them on the client:
    

```javascript
socket.on('chatMessage', (message) => {
    const messagesDiv = document.getElementById('messages');
    const messageElement = document.createElement('div');
    messageElement.textContent = message;
    messagesDiv.appendChild(messageElement);
});
```

---

### **4\. Implementing the Chat Logic on the Server Side**

* **Broadcasting Messages**: Handle incoming messages from clients and broadcast them to all connected clients:
    

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

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

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

---

### **Complete code:**

You can check the complete code below:

```javascript
// server.js
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.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

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

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

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

server.listen(3000, () => {
    console.log('Server running on port 3000');
});
```

```xml
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Chat Application</title>
</head>
<body>
    <div id="messages"></div>
    <input id="messageInput" type="text" placeholder="Enter your message">
    <button id="sendButton">Send</button>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io();

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

        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const messagesDiv = document.getElementById('messages');

        sendButton.addEventListener('click', () => {
            const message = messageInput.value;
            socket.emit('chatMessage', message);
            messageInput.value = '';
        });

        socket.on('chatMessage', (message) => {
            const messageElement = document.createElement('div');
            messageElement.textContent = message;
            messagesDiv.appendChild(messageElement);
        });
    </script>
</body>
</html>
```

To run the server, save both files (`server.js` and `index.html`) in the same directory and then run the following command in your terminal:

```bash
node server.js
```

Your chat application should now be running and accessible at [`http://localhost:3000`](http://localhost:3000) in your web browser.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1715144512761/42bfbb0d-ae03-41da-b1b7-b2a71b19bb62.png align="center")

<details data-node-type="hn-details-summary"><summary>Conclusion</summary><div data-type="detailsContent">This guide provides a step-by-step tutorial on building a real-time chat application using Socket.io and Express in Node.js. It covers setting up the project, creating a chat interface, handling chat events, and implementing server-side chat logic to broadcast messages. By the end of this guide, you'll have a functional chat application accessible via a web browser.</div></details>

**References**

* [Socket.io Documentation](https://socket.io/)
    
* [Express.js Documentation](https://expressjs.com/)
    

**Share Your Thoughts**

Have you [built](https://blog.bytescrum.com/) a real-time chat application with [Socket.io](https://medium.com/swlh/real-time-chat-application-using-socket-io-in-node-js-37806e98918c)? Share your experiences and tips in the comments below!
