Skip to main content
WebSockets Tutorial
CHAPTER 02 Beginner

Understanding Real-Time Communication

Updated: May 14, 2026
15 min read

# CHAPTER 2

Understanding Real-Time Communication

1. Introduction

Before WebSockets became the standard, developers had to rely on clever but inefficient hacks to achieve "real-time" communication on the web. The web was originally designed to be stateless and request-driven: the client asks for data, the server responds, and the connection closes. In this chapter, we will explore the evolution of real-time communication on the web, comparing older techniques like Polling and Long Polling with modern solutions like Server-Sent Events (SSE) and WebSockets.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define "Polling" and explain why it is inefficient.
  • Understand the concept of "Long Polling".
  • Explain the purpose of Server-Sent Events (SSE).
  • Differentiate between unidirectional and bidirectional real-time communication.

3. Beginner-Friendly Explanation

Imagine you are at a restaurant waiting for your food.
  • Polling: You walk up to the kitchen counter every 30 seconds and ask, "Is it ready?" Most of the time, the answer is "No." This is exhausting for you and annoying for the chef.
  • Long Polling: You walk up to the counter and ask, "Is it ready?" The chef says, "Wait right here." You stand there until the food is finally ready, take it, eat it, and then immediately go back and wait for the next course.
  • Server-Sent Events (SSE): You sit at your table. A waiter brings you food automatically whenever a dish is ready. You don't have to ask. However, you cannot talk back to the kitchen; you only receive.
  • WebSockets: You sit at a Chef's Table. You have a direct, open conversation with the chef. The chef hands you food instantly, and you can instantly hand back empty plates or give feedback.

4. Real-World Examples

  • Polling Example: An older news website that automatically reloads the webpage every 5 minutes to fetch the latest headlines.
  • Server-Sent Events Example: A live sports commentary feed where text updates are pushed from the server to your browser, but you (the user) are not sending any messages back.
  • WebSocket Example: A live chat room where everyone is typing and receiving messages simultaneously.

5. Step-by-Step Tutorial

Let's see what a traditional Polling script looks like in JavaScript. While we don't recommend this for real-time apps today, understanding it helps you appreciate WebSockets.

Step 1: Create a function that fetches data from an API. Step 2: Use setInterval() to run this function repeatedly.

6. WebSocket vs Polling Examples

Here is the Polling approach:

7. JavaScript Examples

javascript
1234567891011
// Traditional Polling Approach (Not Recommended for Real-Time)
function checkForUpdates() {
    fetch('https://api.example.com/messages')
        .then(response => response.json())
        .then(data => console.log("New messages: ", data))
        .catch(error => console.error("Error: ", error));
}

// Ask the server every 5 seconds (5000 milliseconds)
// Problem: If there are no new messages, we waste network bandwidth!
setInterval(checkForUpdates, 5000);

8. PHP Examples

If a PHP server is handling the polling request, it just looks like a normal API endpoint:
php
123456789101112
<?php
// An endpoint meant to be polled repeatedly
header(&#039;Content-Type: application/json');

// Connect to database and fetch new messages
$newMessages = get_new_messages_from_db();

echo json_encode([
    &#039;status' => 'success',
    &#039;messages' => $newMessages
]);
?>

9. JSON Examples

The JSON payload returned by a polling request:
json
1234567
{
  "status": "success",
  "messages": [
    { "id": 1, "text": "Are we there yet?" },
    { "id": 2, "text": "No." }
  ]
}

10. Best Practices

  • Use SSE for one-way data: If your app only needs to *receive* live data (like a stock ticker) and doesn't need to send data rapidly, Server-Sent Events are often a simpler, lighter alternative to WebSockets.
  • Avoid standard Polling: Standard polling overloads the server with empty requests. Avoid it unless you are dealing with a legacy API that offers no other real-time mechanism.

11. Common Mistakes

  • Confusing WebSockets with SSE: SSE is unidirectional (Server to Client only). WebSockets are bidirectional (Both Client and Server can talk at any time).
  • Setting polling intervals too low: If you set a polling interval to 500ms, your server might crash under the load of thousands of clients making 2 requests per second.

12. Mini Exercises

  1. 1. Look at a live Google Doc. Is it using one-way or two-way communication? *(Answer: Two-way, because you see others type, and they see you type).*
  1. 2. Look at a live weather radar website. One-way or two-way? *(Answer: One-way. The server pushes radar updates, but you aren't sending radar data back).*

13. Coding Challenges

Challenge 1: Write a mock JavaScript setInterval function that acts like polling, but stops asking after 5 unsuccessful attempts.

14. MCQs with Answers

Question 1

Which technique keeps an HTTP request open until the server has new data to send?

Question 2

What is the main drawback of standard Polling?

15. Interview Questions

  • Q: Explain the difference between Long Polling and WebSockets.
  • Q: If you were building a one-way notification system, would you use WebSockets or Server-Sent Events? Why?

16. FAQs

Q: Is Long Polling still used today? A: Yes. Many robust libraries (like Socket.IO) use Long Polling as a fallback mechanism if WebSockets fail or are blocked by a corporate firewall.

17. Summary

In Chapter 2, we learned that before WebSockets, developers used Polling and Long Polling to simulate real-time experiences. While Server-Sent Events (SSE) provide an excellent solution for unidirectional server-to-client updates, WebSockets remain the gold standard for full, two-way, low-latency communication.

18. Next Chapter Recommendation

Now we know the historical context. But how exactly does a WebSocket connection differ fundamentally from a standard HTTP connection? Proceed to Chapter 3: HTTP vs WebSockets for a deep dive into the network protocols.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·