Skip to main content
WebSockets Tutorial
CHAPTER 05 Beginner

Creating Your First WebSocket Connection

Updated: May 14, 2026
20 min read

# CHAPTER 5

Creating Your First WebSocket Connection

1. Introduction

Enough theory—it is time to code! In this chapter, we will build a functional web page that connects to a WebSocket server. Modern web browsers provide a powerful, built-in JavaScript WebSocket API, meaning we do not need to download or install any third-party libraries to make our client work. We will walk through the exact syntax required to establish a connection.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Instantiate a new WebSocket object in JavaScript.
  • Handle connection states using event listeners.
  • Build a basic HTML UI to show connection status.
  • Connect to a public test WebSocket server.

3. Beginner-Friendly Explanation

Think of the browser's WebSocket API like a smart telephone. When you write new WebSocket(url), you are picking up the phone and dialing the number. But a phone call takes a moment to connect. You can't just start shouting into the receiver instantly. You have to wait for the other person to say "Hello" (the connection opens). To handle this waiting period in JavaScript, we use Event Listeners. We tell JavaScript: "When the line is finally open, run this specific block of code."

4. Real-World Examples

Every time you open a Slack channel, the Slack web app runs code very similar to what we are about to write. It connects to Slack's servers, updates a little green dot on your profile to show you are "Online," and prepares to receive new messages.

5. Step-by-Step Tutorial

Let's build a simple HTML page that connects to a free, public echo server (wss://echo.websocket.events). An echo server simply takes whatever message you send it and immediately sends it right back to you.

Step 1: Create a basic HTML file with an element to display our status. Step 2: Write a <script> tag. Step 3: Create the WebSocket instance. Step 4: Add an onopen event listener to change the HTML text when connected.

6. Client Connection Example

Here is the complete HTML and JavaScript code. You can save this as an .html file and double-click it to run it in your browser!

7. HTML & JavaScript Examples

html
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First WebSocket</title>
    <!-- Using a bit of TailwindCSS for basic styling -->
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center h-screen">

    <div class="bg-white p-8 rounded shadow-md text-center">
        <h1 class="text-2xl font-bold mb-4">WebSocket Status</h1>
        
        <!-- This span will update when we connect -->
        <span id="status" class="px-4 py-2 rounded font-bold bg-yellow-200 text-yellow-800">
            Connecting...
        </span>
    </div>

    <script>
        // Step 1: Define the server URL
        const serverUrl = "wss://echo.websocket.events";

        // Step 2: Create the WebSocket connection
        const socket = new WebSocket(serverUrl);

        // Step 3: Get a reference to our UI element
        const statusElement = document.getElementById("status");

        // Step 4: Listen for the 'open' event
        socket.onopen = function(event) {
            console.log("Handshake complete! Connection is open.");
            
            // Update the UI to show success
            statusElement.innerText = "Connected! 🟢";
            statusElement.className = "px-4 py-2 rounded font-bold bg-green-200 text-green-800";
        };
        
        // Listen for connection close
        socket.onclose = function(event) {
            statusElement.innerText = "Disconnected 🔴";
            statusElement.className = "px-4 py-2 rounded font-bold bg-red-200 text-red-800";
        };
    </script>
</body>
</html>

8. PHP Backend Context

If you were writing the backend for this in PHP, you would start a WebSocket server daemon that listens on a specific port. The server waits patiently until a client runs new WebSocket() and then accepts the connection. (We will build the PHP server in Chapter 18).

9. Examining the WebSocket Object

If you console.log(socket) immediately after creating it, you will see a readyState property. It uses numbers to track the status:
  • 0 (CONNECTING): The handshake is happening.
  • 1 (OPEN): The connection is ready to send and receive.
  • 2 (CLOSING): The connection is in the process of shutting down.
  • 3 (CLOSED): The connection has been terminated.

10. Best Practices

  • Never block the main thread: JavaScript is single-threaded. Because WebSockets use event listeners, they run asynchronously. Creating a connection will not freeze your webpage while it waits for the server to respond.
  • Check readyState before acting: Before trying to do anything advanced with your socket, always ensure socket.readyState === WebSocket.OPEN.

11. Common Mistakes

  • Trying to send data immediately: A very common beginner mistake is writing const ws = new WebSocket(url); ws.send("Hi"); on the next line. This will throw an error because the connection takes a few milliseconds to open. You *must* put the .send() inside the onopen callback.

12. Mini Exercises

  1. 1. Copy the code in Section 7 into a file named index.html.
  1. 2. Open it in your web browser. You should see "Connecting..." briefly change to "Connected! 🟢".
  1. 3. Turn off your Wi-Fi/Internet and refresh the page. What happens? *(It stays on Connecting... and eventually fails).*

13. Coding Challenges

Challenge 1: Modify the JavaScript to log the exact readyState number to the console before the onopen event fires, and then log it again inside the onopen event. (You should see 0, then 1).

14. MCQs with Answers

Question 1

What is the correct way to initialize a WebSocket connection in modern browsers?

Q2. Why will the following code fail?
javascript
12
const ws = new WebSocket("wss://echo.websocket.events");
ws.send("Hello!");

A) You cannot send strings, only JSON. B) The connection has not finished opening yet. C) The URL is missing the port number. D) send() is not a valid method. *Answer: B*

15. Interview Questions

  • Q: Explain the four readyState constants of a WebSocket object.
  • Q: Why do we use asynchronous event listeners (onopen, onmessage) when working with WebSockets?

16. FAQs

Q: Can I connect to multiple WebSocket servers at the same time? A: Absolutely! You can instantiate new WebSocket() as many times as you want, pointing to different servers, and handle them simultaneously. (e.g., One for chat, one for live stock prices).

17. Summary

In Chapter 5, we wrote our first lines of real WebSocket code. We learned how to instantiate the WebSocket object, point it to a secure wss:// URI, and use the onopen event listener to safely execute code only after the handshake is successfully completed.

18. Next Chapter Recommendation

Now that our connection is open and active, we need to actually talk to the server! Proceed to Chapter 6: Sending and Receiving Messages, where we will learn how to transmit data and listen for the server's replies.

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