Creating Your First WebSocket Connection
# 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 JavaScriptWebSocket 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
WebSocketobject 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'sWebSocket 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
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 runsnew WebSocket() and then accepts the connection. (We will build the PHP server in Chapter 18).
9. Examining the WebSocket Object
If youconsole.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
readyStatebefore acting: Before trying to do anything advanced with your socket, always ensuresocket.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 theonopencallback.
12. Mini Exercises
-
1.
Copy the code in Section 7 into a file named
index.html.
- 2. Open it in your web browser. You should see "Connecting..." briefly change to "Connected! 🟢".
- 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 exactreadyState 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
What is the correct way to initialize a WebSocket connection in modern browsers?
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
readyStateconstants 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 instantiatenew 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 theWebSocket 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.