WebSockets provide a persistent connection between a client and a server, enabling real-time, bidirectional communication. This makes them ideal for applications like chat, online games, and live dashboards. Socket.IO is a library that simplifies the use of WebSockets, providing fallbacks for older browsers and adding useful features like rooms and namespaces.
In this blog post, we’ll walk through building a basic chat application using Node.js, Express, and Socket.IO.
Prerequisites:
- Node.js and npm installed.
Setting up the Project:
- Create a project directory:
- Bash
mkdir real-time-chat cd real-time-chat
- Initialize a Node.js project:
- Bash
npm init -y
- Install Express and Socket.IO:
- Bash
npm install express socket.io
Creating the Server (server.js):
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files (HTML, CSS, JS) from the 'public' directory
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Broadcast the message to all connected clients
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Explanation:
- We create an Express application and an HTTP server.
- We initialize Socket.IO with the HTTP server.
app.use(express.static('public'))serves static files from thepublicdirectory.io.on('connection', (socket) => { ... })handles new client connections.socket.on('chat message', (msg) => { ... })listens for ‘chat message’ events from the client and broadcasts them to all connected clients usingio.emit().socket.on('disconnect', () => { ... })handles client disconnections.
Creating the Client (public/index.html):
HTML
<!DOCTYPE html>
<html>
<head>
<title>Chat Application</title>
<style>
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
#input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
#button { background: rgb(130, 224, 255); border: none; padding: 10px; width: 9%; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input type="text" 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', (e) => {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>
Explanation:
- We include the Socket.IO client library (
/socket.io/socket.io.js). - We initialize a Socket.IO connection using
io(). - We listen for form submissions and emit ‘chat message’ events to the server.
- We listen for ‘chat message’ events from the server and append them to the message list.
Running the Application:
- Create a
publicdirectory in your project root. - Save the
index.htmlfile in thepublicdirectory. - Save the
server.jsfile in your project root. - Run the server:
- Bash
node server.js
- Open your browser and navigate to
http://localhost:3000. - Open multiple browser tabs or windows to see the real-time chat in action.
Further Enhancements:
- Usernames: Add username functionality to identify users.
- Rooms: Implement chat rooms for different topics or groups.
- Private Messages: Allow users to send private messages to each other.
- Typing Indicators: Show when a user is typing.
- Message History: Store and display previous messages.
- Styling: Enhance the UI with CSS.
- Deployment: Deploy your application to a hosting platform.
Socket.IO makes it easy to build real-time applications with WebSockets. By leveraging its features, you can create engaging and interactive experiences for your users.
