Learn Node.js ยท 11/13

Real-time Communication: Adding WebSockets

8 min read

Real-time Communication: Adding WebSockets WebSocket

Welcome! Let's dive into the exciting world of real-time communication with Node.js. In this guide, we'll explore how to make your applications interactive and dynamic using WebSockets.


1. Beyond HTTP: Introduction to WebSockets ๐ŸŒ

The Problem with HTTP for Real-time

Imagine you're at a restaurant (your client) and you want to know when your order is ready. Using traditional HTTP, you would have to keep calling the waiter (the server) every few seconds and asking, "Is my food ready yet?". This is inefficient and annoying for both you and the waiter. This process is called polling.

The WebSocket Solution

Now, what if the waiter could just tap you on the shoulder the moment your food is ready? That's essentially what WebSockets do.

A WebSocket is a communication protocol that provides a full-duplex communication channel over a single, long-lived TCP connection. In simpler terms, it's a persistent, two-way conversation between the client and the server. Once the connection is established, both the client and the server can send data to each other at any time, without the need for the client to repeatedly ask for updates.

This makes WebSockets ideal for applications that require real-time data exchange, such as:

  • Chat applications ๐Ÿ’ฌ
  • Live sports updates โšฝ
  • Real-time collaboration tools ๐Ÿ“
  • Online multiplayer games ๐ŸŽฎ

Think of it like a dedicated phone line between the client and the server. The line is always open, and either party can start talking whenever they have something to say.


2. Integrating Socket.io with an Express Server ๐Ÿค

While you can use the native WebSocket API, a library called Socket.io makes working with WebSockets much easier and adds some helpful features. Socket.io will gracefully fall back to other technologies like long-polling if WebSockets aren't available, ensuring your real-time features work for a wider range of users.

Let's set up a basic Express server and add Socket.io to it.

Getting Started

First, make sure you have Node.js and npm installed. Then, create a new project directory, initialize a package.json file, and install the necessary dependencies.

bash
mkdir real-time-app
cd real-time-app
npm init -y
npm install express socket.io

Now, create a file named server.js and add the following code:

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

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`listening on *:${PORT}`);
});

Let's break down what's happening here:

  1. We're importing the necessary modules: express, the built-in http module, and the Server class from socket.io.
  2. We create an Express app and then an HTTP server from that app.
  3. We instantiate a new Server from socket.io and pass it our HTTP server. This is how Socket.io hooks into our server.
  4. We set up a simple route to serve an index.html file (which we'll create next).
  5. The io.on('connection', ...) part is where the Socket.io magic begins. It listens for incoming connections and logs a message to the console whenever a new client connects.

Next, create an index.html file in the same directory:

html
<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
  </head>
  <body>
    <h1>Hello world</h1>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();
    </script>
  </body>
</html>

The key part of this HTML file is the <script src="/socket.io/socket.io.js"></script> line. This file is automatically served by the Socket.io server and provides the client-side library. Then, const socket = io(); establishes the WebSocket connection from the client to the server.

Now, you can run your server:

bash
node server.js

If you open your browser to http://localhost:3000, you should see "Hello world" and in your terminal, you'll see the message "a user connected". Congratulations, you've established a real-time connection! ๐ŸŽ‰


3. Event Driven Communication: Broadcasting and Emitting ๐Ÿ“ก

Socket.io is event-driven. This means that both the client and the server communicate by sending and receiving named events. You can think of these as custom messages that you define.

Emitting and Listening

The two main methods you'll use are .emit() to send an event and .on() to listen for an event.

Let's modify our server.js and index.html to send a "welcome" message to a newly connected user.

Server-side (server.js)

javascript
// ... (previous server setup)

io.on('connection', (socket) => {
  console.log('a user connected');
  
  // Send a message to the newly connected client
  socket.emit('welcome', 'Welcome to the real-time world!');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

// ... (rest of the server setup)

Client-side (index.html)

html
<!-- ... (previous html setup) -->
    <script>
      const socket = io();

      // Listen for the 'welcome' event from the server
      socket.on('welcome', (message) => {
        console.log(message); // This will log "Welcome to the real-time world!"
      });
    </script>
<!-- ... (rest of the html setup) -->

Now, when a user connects, the server emits a welcome event with a message. The client is listening for this welcome event and will log the message to the browser's console.

Broadcasting

Broadcasting means sending a message to all connected clients. This is useful for things like a public chat message where everyone should see it.

To broadcast a message, you use io.emit().

Let's say we want to notify everyone when a new user joins.

Server-side (server.js)

javascript
// ... (previous server setup)

io.on('connection', (socket) => {
  console.log('a user connected');
  
  // Broadcast to all clients that a new user has connected
  io.emit('user joined', 'A new user has joined the chat!');

  // ... (rest of the connection logic)
});

// ... (rest of the server setup)

Client-side (index.html)

html
<!-- ... (previous html setup) -->
    <script>
      const socket = io();

      // ... (other event listeners)

      // Listen for the 'user joined' event
      socket.on('user joined', (message) => {
        const item = document.createElement('li');
        item.textContent = message;
        document.querySelector('ul').appendChild(item);
      });
    </script>
<!-- ... (rest of the html setup) -->

Now, whenever a new user connects, every connected client (including the new one) will receive the user joined event and update their UI accordingly.

Sometimes, you want to broadcast a message to everyone except the client that sent the message. This is useful for chat applications where you don't want to see your own message appear twice. For this, you can use socket.broadcast.emit().

Server-side (server.js)

javascript
// ... (previous server setup)

io.on('connection', (socket) => {
  // ...

  // Listen for a 'chat message' event from a client
  socket.on('chat message', (msg) => {
    // Broadcast the message to everyone except the sender
    socket.broadcast.emit('chat message', msg);
  });
});

// ... (rest of the server setup)

In this example, when the server receives a chat message from one client, it sends that same message to all other connected clients. The original sender will not receive this message back from the server.


4. Practical Build: A Real-time Chat Feature ๐Ÿ› ๏ธ

Let's put everything we've learned together to build a simple real-time chat application.

Final server.js

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

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');

  // Listen for chat messages
  socket.on('chat message', (msg) => {
    // Broadcast the message to everyone
    io.emit('chat message', msg);
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`listening on *:${PORT}`);
});

Final index.html

html
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input 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) {
          // Emit a 'chat message' event to the server
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

      // Listen for 'chat message' events from the server
      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>

Now, if you run node server.js and open http://localhost:3000 in multiple browser tabs, you can send messages from one tab and they will appear in all the other tabs in real-time. How cool is that? ๐Ÿ˜Ž

This simple example demonstrates the power of WebSockets and Socket.io for building interactive and engaging web applications.


Further Reading and Resources ๐Ÿ“š

Challenge

You are tasked with building the backend logic for a real-time user counter. A server has been partially set up using Express and Socket.io. Your goal is to complete the logic to track the number of connected clients and notify all clients whenever this number changes.

Requirements:

  1. A variable named userCount has been initialized to track the number of connected users.
  2. When a new client establishes a connection within the io.on('connection', ...) handler:
    • Increment the userCount.
    • Broadcast an event named userCountUpdate to all connected clients. The event must carry the updated userCount as its data.
  3. When a client disconnects, within the socket.on('disconnect', ...) handler:
    • Decrement the userCount.
    • Broadcast an event named userCountUpdate to all remaining connected clients, sending the newly updated userCount.

Expected result

Your submitted code should be a complete server.js file that correctly implements the real-time user counter.

The correct solution will contain the following logic:

  • Inside the 'connection' event handler, the userCount is incremented, and io.emit('userCountUpdate', userCount) is called immediately after to inform all clients of the new total.
  • Inside the nested 'disconnect' event handler, the userCount is decremented, and io.emit('userCountUpdate', userCount) is called to inform all remaining clients of the change.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.