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.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers 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

  1. Adding a username: Modify the chat app to include a username with each message.
  2. Private messages: Implement private messaging between two users.
  3. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help