Express.js / Express.js and WebSockets

Handling Real-Time Communication with WebSockets

This tutorial provides a deep dive into handling real-time communication with WebSockets, enabling you to create interactive and responsive web applications.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers integrating WebSockets for real-time communication in Express applications.

Introduction

The goal of this tutorial is to provide an in-depth understanding of how to use WebSockets for real-time communication in your web applications. By the end of this tutorial, you'll be able to build a simple chat application that can send and receive messages in real-time.

Prerequisites include basic knowledge of JavaScript, HTML, and Node.js. Familiarity with Express.js will also be beneficial but is not a requirement.

Step-by-Step Guide

WebSockets is a protocol that provides full-duplex communication channels over a single TCP connection. It allows servers to push updates to clients as they happen, leading to efficient real-time communication.

Creating a WebSocket Server

We'll be using Node.js and Express.js to create a WebSocket server. First, install the necessary dependencies:

npm install express ws

Here is a simple WebSocket server:

const express = require('express');
const WebSocket = require('ws');

const app = express();
const PORT = 3000;

const wss = new WebSocket.Server({ noServer: true });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log('Received: ', message);
    ws.send(`Server response: ${message}`);
  });

  ws.send('Hello from server!');
});

const server = app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

server.on('upgrade', (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});

Creating a WebSocket Client

On the client-side, we can create a WebSocket connection to our server:

const socket = new WebSocket('ws://localhost:3000');

socket.addEventListener('open', (event) => {
  socket.send('Hello Server!');
});

socket.addEventListener('message', (event) => {
  console.log('Message from server: ', event.data);
});

Code Examples

Let's take a look at a few more examples.

  1. Broadcasting messages to all connected clients
wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(`Broadcast: ${message}`);
      }
    });
  });
});
  1. Handling close events
ws.on('close', () => {
  console.log('Client disconnected');
});

Summary

In this tutorial, we've learned how to create a WebSocket server and client, and how to handle messages and events. Next, you could explore more about handling different types of data, such as binary data or JSON.

You may find the following resources helpful:

Practice Exercises

  1. Simple Echo Server: Create a WebSocket server that sends back any message it receives.
  2. Chat Application: Extend the echo server to broadcast messages to all connected clients.
  3. Real-time Updates: Create an application that sends real-time updates from the server to the client, such as a simple clock that sends the current time every second.

Here's a hint for the third exercise: you can use JavaScript's setInterval function to send a message every second:

setInterval(() => {
  ws.send(`The time is ${new Date()}`);
}, 1000);

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

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

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