Express.js / Express.js and WebSockets
Building a Chat Application with Socket.io
This tutorial walks you through building a real-time chat application using Socket.io, allowing you to put into practice your knowledge of WebSockets and real-time event handling.
Section overview
5 resourcesCovers integrating WebSockets for real-time communication in Express applications.
1. Introduction
In this tutorial, we'll be learning how to build a real-time chat application using Socket.io. This chat application will allow users to send and receive messages instantly.
You will learn how to:
- Set up a server with Node.js and Express
- Establish a real-time bi-directional communication between the server and the client with Socket.io
- Broadcast messages to connected users
Prerequisites:
- Basic knowledge of JavaScript
- Node.js and npm installed on your machine
2. Step-by-Step Guide
2.1 Setting up the Server
We'll start by setting up a server using Node.js and Express. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
// Import express and create an app
const express = require('express');
const app = express();
// Define a route handler for the default home page
app.get('/', (req, res) => {
res.send("Hello World!");
});
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
2.2 Integrating Socket.io
Socket.io enables real-time, bidirectional and event-based communication. It works on every platform, browser, or device, focusing equally on reliability and speed.
// Import socket.io with a connection to a server obtained from a http server
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// Listen on the connection event for incoming sockets
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
3. Code Examples
3.1 Sending and Receiving Messages
Now we'll implement the core functionality of our chat app: sending and receiving messages.
io.on('connection', (socket) => {
console.log('a user connected');
// Listen for chat message event
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
// Emit the message to all connected clients
io.emit('chat message', msg);
});
});
In this code snippet, we listen for the 'chat message' event, log the message to the console, and then emit the message to all connected clients.
3.2 Disconnecting a Socket
We also want to handle the case where a user disconnects from the chat.
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
// Listen for disconnect event
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
4. Summary
In this tutorial, we learned how to build a real-time chat application using Socket.io. We covered setting up a server with Node.js and Express, integrating Socket.io, and sending/receiving messages.
Next steps for learning would be to explore more features of Socket.io, like rooms and namespaces, and to experiment with storing messages in a database.
Additional resources include the Socket.io Documentation.
5. Practice Exercises
- Adding a username: Modify the chat app to include a username with each message.
- Private messages: Implement private messaging between two users.
- Chat history: Store chat history and display it to users when they join the chat.
Each of these exercises can be solved by applying what we've already learned and looking up additional information in the Socket.io documentation. For further practice, consider exploring other real-time data use-cases, like live updates in a dashboard application.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article