Skip to main content
WebSockets Tutorial
CHAPTER 01 Beginner

Introduction to WebSockets

Updated: May 14, 2026
10 min read

# CHAPTER 1

Introduction to WebSockets

1. Introduction

Welcome to the WebSockets tutorial! In the modern web, users expect information to update instantly. When you receive a message on WhatsApp, see a live score change, or watch stock prices tick up and down, you are experiencing real-time communication. WebSockets are the underlying technology that makes these seamless, instant updates possible. In this chapter, we will introduce what WebSockets are and why they are essential for modern web development.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand what WebSockets are and how they differ from traditional web requests.
  • Explain why real-time communication is critical in modern applications.
  • Identify common use cases for WebSockets.
  • Connect to a public echo server using basic JavaScript.

3. Beginner-Friendly Explanation

Imagine you are waiting for a package delivery. In the traditional web approach, you have to call the delivery company every 5 minutes and ask, "Is my package here yet?" This is annoying for you and overwhelming for the company. With WebSockets, it's like giving the delivery driver your phone number. You connect once, and the driver instantly sends you a text message the exact second your package arrives at your door. You don't have to keep asking; the server just pushes the information to you the moment it happens!

4. Real-World Examples

  • Chat Applications: WhatsApp, Slack, and Discord use real-time connections so you see messages the millisecond they are sent.
  • Multiplayer Games: When you move your character in an online game, WebSockets instantly send that movement to all other players.
  • Financial Dashboards: Cryptocurrency trackers or stock market tickers that flash green and red use WebSockets for live price feeds.
  • Collaborative Tools: Google Docs or Figma, where you can see another person's cursor moving on your screen in real time.

5. Step-by-Step Tutorial

Let's look at how simple it is to establish a connection. The browser has a built-in WebSocket API, so you don't even need to install any external libraries!

Step 1: Create a new WebSocket object, pointing to a server URL. (Notice it starts with wss:// instead of https://). Step 2: Attach an event listener to know when the connection is open. Step 3: Send a message to the server. Step 4: Listen for messages coming back from the server.

6. WebSocket Examples

Here is the simplest flow of connecting and sending data.

7. JavaScript Examples

javascript
123456789101112131415
// Step 1: Connect to a public test server (echo server)
const socket = new WebSocket("wss://echo.websocket.org/");

// Step 2: Connection opened
socket.onopen = (event) => {
    console.log("Connected to the WebSocket server!");
    
    // Step 3: Send a message
    socket.send("Hello, Server! I am learning WebSockets.");
};

// Step 4: Listen for incoming messages
socket.onmessage = (event) => {
    console.log("Message from server: " + event.data);
};

8. PHP Examples

While PHP is traditionally used for standard web pages, it can also run WebSocket servers! We will explore this deeply in later chapters, but here is a conceptual look:
php
123456789
<?php
// Conceptual WebSocket connection in PHP (Requires libraries like Ratchet)
// The server waits for connections and instantly broadcasts messages
$server->on(&#039;message', function ($connection, $message) {
    echo "Received message: " . $message;
    // Echo the message back
    $connection->send("You said: " . $message);
});
?>

9. JSON Examples

When communicating via WebSockets, we usually send data as JSON strings so both client and server understand the structure.
json
12345
{
  "type": "greeting",
  "text": "Hello, Server! I am learning WebSockets.",
  "timestamp": "2026-05-15T10:00:00Z"
}

10. Best Practices

  • Use Secure WebSockets: Always use wss:// (WebSocket Secure) instead of ws:// in production, just like you use HTTPS.
  • Handle Disconnections: Networks are unreliable. Always write code to reconnect if the WebSocket connection drops unexpectedly.
  • Keep Payloads Small: Send only the data you need to ensure fast, low-latency transmission.

11. Common Mistakes

  • Assuming WebSockets replace HTTP: WebSockets are great for real-time data, but HTTP is still better for loading standard web pages, images, and heavy files. Use both!
  • Forgetting to stringify JSON: You cannot send a raw JavaScript object over a WebSocket; you must use JSON.stringify() before sending and JSON.parse() when receiving.

12. Mini Exercises

  1. 1. Open your browser's Developer Tools (F12) right now.
  1. 2. Go to the "Console" tab.
  1. 3. Paste the JavaScript example from Section 7 into the console and press Enter.
  1. 4. Watch the console to see the server echo your message back to you!

13. Coding Challenges

Challenge 1: Modify the JavaScript example above. Instead of sending a simple string, create a JavaScript object with your name and age, convert it to a JSON string, and send it to the echo server.

14. MCQs with Answers

Question 1

What protocol prefix is used for secure WebSocket connections?

Question 2

What does a WebSocket connection provide that traditional HTTP does not?

15. Interview Questions

  • Q: Explain WebSockets to a non-technical person.
  • Q: When would you choose to use a WebSocket instead of standard REST API requests?
  • Q: Why do we use JSON over WebSockets instead of raw text?

16. FAQs

Q: Do WebSockets work on mobile phones? A: Yes! WebSockets are supported in all modern mobile browsers (Safari on iOS, Chrome on Android).

Q: Are WebSockets only for JavaScript? A: No, the client is usually JavaScript (in the browser), but the server can be written in PHP, Node.js, Python, Java, or any other backend language.

17. Summary

In Chapter 1, we introduced WebSockets, a revolutionary protocol that allows persistent, two-way communication between a browser and a server. By eliminating the need for the browser to constantly "ask" for updates, WebSockets enable real-time features like chat apps, live dashboards, and multiplayer games.

18. Next Chapter Recommendation

Now that you know what WebSockets are, how did we do this before WebSockets existed? Proceed to Chapter 2: Understanding Real-Time Communication, where we will explore older techniques like Polling and Server-Sent Events, and see why WebSockets are the ultimate solution.

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: ·