Skip to main content
WebSockets Tutorial
CHAPTER 07 Beginner

WebSocket Events Explained

Updated: May 14, 2026
20 min read

# CHAPTER 7

WebSocket Events Explained

1. Introduction

A WebSocket client is entirely event-driven. Instead of writing linear code that executes from top to bottom, you write functions that wait patiently for specific moments in time—events—to occur. The JavaScript WebSocket API provides four primary events to manage the entire lifecycle of a connection. In this chapter, we will master onopen, onmessage, onerror, and onclose.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the four core WebSocket events.
  • Implement robust error handling using onerror.
  • Interpret the CloseEvent to determine why a connection dropped.
  • Distinguish between clean and dirty disconnections.

3. Beginner-Friendly Explanation

Think of your WebSocket as a phone call with four distinct stages:
  1. 1. onopen (The Greeting): The other person picks up and says, "Hello, I'm here." You can now start talking.
  1. 2. onmessage (The Conversation): The other person says something to you. You listen and react.
  1. 3. onerror (The Static): The connection gets staticky, or you hear a loud interference noise. Something went wrong!
  1. 4. onclose (The Hangup): You hear the click and the dial tone. The call has ended. You might have hung up on purpose, or you might have driven into a tunnel and lost the signal.

4. Real-World Examples

  • onerror in action: A user on a train connects to your chat app. The train goes into a tunnel, completely killing their internet. The browser detects the socket failure and fires onerror.
  • onclose in action: A server administrator needs to restart the WebSocket server for maintenance. The server gracefully sends a Close frame to all clients. The clients' onclose events fire with a message saying "Server restarting."

5. Step-by-Step Tutorial

Let's build a complete, resilient WebSocket client that listens to all four events and logs exactly what is happening to the user interface.

Step 1: Create the WebSocket object. Step 2: Attach onopen to handle setup. Step 3: Attach onmessage to handle data. Step 4: Attach onerror to catch connection faults. Step 5: Attach onclose to handle cleanup and read the disconnection reason.

6. Comprehensive Events Example

Here is the standard boilerplate every professional frontend developer uses when establishing a WebSocket.

7. JavaScript Examples

javascript
1234567891011121314151617181920212223242526272829
const socket = new WebSocket("wss://echo.websocket.events");

// 1. Connection opens
socket.onopen = function(event) {
    console.log("🟢 Connection established successfully.");
    // Safe to send initial data now
    socket.send("Hello Server!");
};

// 2. Message received
socket.onmessage = function(event) {
    console.log("✉️ New message received: ", event.data);
};

// 3. Error occurs
socket.onerror = function(event) {
    // Note: The onerror event doesn't provide deep details due to browser security rules.
    console.error("🔴 WebSocket encountered an error!");
};

// 4. Connection closes
socket.onclose = function(event) {
    if (event.wasClean) {
        console.log(`🔌 Closed cleanly. Code: ${event.code}, Reason: ${event.reason}`);
    } else {
        // e.g., server process killed or network down
        console.warn('⚠️ Connection died abruptly (Dirty close).');
    }
};

8. The CloseEvent Object

When onclose fires, it receives a CloseEvent object containing vital debugging info:
  • event.wasClean: A boolean. If true, the client and server completed the formal closing handshake. If false, the connection snapped unexpectedly.
  • event.code: A numerical status code. (e.g., 1000 = Normal Closure, 1006 = Abnormal Closure/Dropped, 1011 = Server Error).
  • event.reason: A string provided by the server explaining why it closed the connection (e.g., "User kicked for inactivity").

9. Closing the Connection Manually

You don't have to wait for the server to hang up. You can close the connection from the client using socket.close().
javascript
12
// Close the connection with a specific code and reason
socket.close(1000, "User clicked the logout button.");

10. Best Practices

  • Don't rely solely on onerror for details: Browsers intentionally hide the exact details of network errors in the onerror event to prevent hackers from fingerprinting the server. Always log the error on the *server side* for true debugging.
  • Always handle onclose: Because networks are unpredictable, your connection *will* drop eventually. Your onclose listener is where you should trigger your UI to show a "Reconnecting..." banner.

11. Common Mistakes

  • Assuming onclose fires immediately when Wi-Fi drops: If a user loses Wi-Fi abruptly, the browser might not realize the TCP connection is dead until a few minutes pass without receiving a Ping/Pong. This results in a delayed onclose event.

12. Mini Exercises

  1. 1. Using the code from Section 7, open your browser console.
  1. 2. Type socket.close() and hit enter.
  1. 3. Observe what prints to the console. You should see the clean closure message with code 1005 or 1000.

13. Coding Challenges

Challenge 1: Write a wrapper function around socket.close() that disables your app's "Send" button immediately before shutting down the socket, preventing users from trying to type while disconnected.

14. MCQs with Answers

Question 1

Which event fires when the connection is lost due to an unexpected internet outage?

Question 2

Can you send a custom message to the server when you close the connection from the client side?

15. Interview Questions

  • Q: Explain the difference between a "clean" close and a "dirty" close in WebSockets.
  • Q: How can you determine exactly why a WebSocket server decided to disconnect your client?

16. FAQs

Q: Does onerror always mean the connection is dead? A: Almost always. According to the WebSocket spec, if onerror fires, an onclose event will follow immediately after it. You cannot "recover" from an error; you must create a new connection.

17. Summary

In Chapter 7, we mastered the four fundamental events of the WebSocket API. By effectively utilizing onopen, onmessage, onerror, and onclose, we can build robust applications that respond intelligently to the full lifecycle of a network connection, including graceful handling of failures and disconnections.

18. Next Chapter Recommendation

We now have all the tools required to build a real project! Proceed to Chapter 8: Building a Real-Time Chat Application, where we will combine everything we've learned to construct a functional UI with Alpine.js and TailwindCSS.

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