Understanding Sockets

Hello again, and welcome to one of my favorite sections. In this lesson, we're diving into something fundamental to the internet: sockets.

Why Learn About Sockets?

You might be thinking, "I know what HTTP is. I know how to make requests. So what's all this about sockets, and why do I even need them?"

Bear with me. By the end of this lesson, you’ll know more about sockets than most senior developers. You’ll also be able to use this knowledge to create some really cool and unique web applications.

The Problem: Real-Time Communication

Let’s start with a familiar example. Imagine a chat application like Discord or WhatsApp. Here’s what you know:

  • Sending Messages: When you send a message, it’s typically a POST request to the server.

  • Fetching Messages: When you want to see messages sent by others, it’s a GET request to the server.

So far, so good. But here’s the big question:

How do you know when someone sends you a message?

You can’t predict when someone will type or send something. They might respond immediately, hours later, or even days later. So how do we know when to ask the server for new messages?

This is where sockets come in. But before diving into sockets, let’s explore a common approach using what we already know.

Polling: A Basic Approach

In situations where the timing of new data is unpredictable, we often use a method called polling. Polling means making a GET request at regular intervals to check for new data. Let’s see how this works.

Example: Polling in a Chat Application

Here’s how polling might look in code:

// Define the polling rate
const pollingRate = 500; // 500 milliseconds

// Use setInterval to make a request every polling interval
setInterval(async () => {
    try {
        // Fetch messages from the server
        const response = await fetch('https://api.mychatapp.com/messages');
        const messages = await response.json();

        // Update the application state with new messages
        console.log(messages);
    } catch (error) {
        console.error('Error fetching messages:', error);
    }
}, pollingRate);

In this example:

  • The polling rate is set to 500 milliseconds.

  • Every 500 milliseconds, the application makes a GET request to fetch new messages from the server.

  • The fetched messages are then used to update the application state.

Issues with Polling

While polling works, it has some drawbacks:

  1. Latency: Even with a 500ms polling rate, there’s always a delay before new data is fetched.

  2. Overhead: Polling generates a lot of requests. For example, at 2 requests per second, that’s 120 requests per minute per user. This can strain your server and increase costs.

  3. Inefficiency: Most requests may return no new data, especially when updates are infrequent.

Polling might be acceptable for chat applications, but it’s unsuitable for scenarios requiring real-time updates, such as:

  • Stock trading

  • Self-driving cars

  • Multiplayer games (e.g., Pong or other fast-paced applications)

Imagine a multiplayer Pong game. A 500ms delay could mean the difference between hitting the ball and losing the game!

Enter Sockets

This is where sockets save the day. Sockets enable real-time, two-way communication between the client and server. Instead of repeatedly asking the server for updates, the server pushes updates to the client as soon as they happen.

In the next sections, we’ll dive deeper into:

  1. What sockets are and how they work.

  2. How to set up a socket connection.

  3. Real-world use cases for sockets.

  4. Building a real-time application using sockets.

Stay tuned—we’re just getting started!