Handling Real-Time Communication with WebSockets

Tutorial 2 of 5

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);