Sending and Receiving Messages
# CHAPTER 6
Sending and Receiving Messages
1. Introduction
Once a WebSocket connection is successfully established, the real fun begins. The primary purpose of this persistent connection is to push data rapidly between the client and the server. In this chapter, we will learn how to send messages from the browser to the server using the.send() method, and how to capture incoming messages from the server using the onmessage event listener.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Transmit text data using
socket.send().
-
Set up an
onmessageevent listener to catch server responses.
-
Extract the payload data from a
MessageEventobject.
- Build a simple two-way interactive UI.
3. Beginner-Friendly Explanation
Imagine you are playing a game of catch.-
Throwing the ball: When you want to throw the ball to your partner (the server), you physically toss it. In JavaScript, this action is
socket.send("Catch!").
-
Catching the ball: When your partner throws it back, you need to be paying attention so it doesn't hit you in the face. In JavaScript, you stand ready by setting up an
onmessagelistener. Whenever a ball arrives, this listener fires, allowing you to catch the ball and look at what is written on it.
4. Real-World Examples
-
Chat Apps: When you type "Hello" and hit Enter, the app runs
send("Hello"). When your friend replies, youronmessagelistener catches their reply and adds it to the screen.
-
Stock Tickers: The client connects, and the server continuously fires messages to the client's
onmessagelistener every time a stock price changes.
5. Step-by-Step Tutorial
Let's build upon the UI we created in the last chapter. We will add an input field, a "Send" button, and a box to display the messages we get back from the echo server.Step 1: Add an input field and a button to your HTML.
Step 2: Ensure the WebSocket connects.
Step 3: Add an onclick event to the button that grabs the input text and runs socket.send().
Step 4: Add an onmessage event listener to append the server's response to the webpage.
6. Interactive App Example
Here is the complete code for a functional Echo Chat interface.7. HTML & JavaScript Examples
8. The MessageEvent Object
Whenonmessage fires, it receives an event object. This object contains several properties, but the most important one is event.data.
If the server sends text, event.data is a String. If the server sends binary data (like an image), event.data will be a Blob or an ArrayBuffer.
9. JSON Data Handling
Usually, we send more complex data than simple strings. We must useJSON.stringify to send, and JSON.parse to receive.
10. Best Practices
-
Validate
readyState: Always wrap yoursocket.send()in a check to ensurereadyState === WebSocket.OPEN. If a user clicks "Send" while the connection is dropped, your app will crash.
-
Use Try/Catch for JSON: When parsing
event.datausingJSON.parse(), wrap it in atry...catchblock. If the server accidentally sends plain text,JSON.parsewill throw a fatal error.
11. Common Mistakes
-
Sending DOM elements: You cannot do
socket.send(msgInput). You must send the *value* of the input:socket.send(msgInput.value). WebSockets only understand strings and binary data, not HTML elements.
12. Mini Exercises
- 1. Run the code from Section 7.
- 2. Type "Hello Server" and hit Send.
- 3. Look closely at the chat box. You should see "You: Hello Server" instantly, followed a millisecond later by "Server: Hello Server" as the echo returns.
13. Coding Challenges
Challenge 1: Modify theonmessage function from Section 7 so that if the server echoes back the exact word "PING", the client automatically replies by running socket.send("PONG").
14. MCQs with Answers
Which property of the onmessage event contains the actual message payload sent by the server?
What happens if you call socket.send("Hi") when socket.readyState is 3 (CLOSED)?
15. Interview Questions
- Q: How do you safely send a complex nested JavaScript object over a WebSocket?
-
Q: Why is it dangerous to blindly
JSON.parse(event.data)without a try/catch block?
16. FAQs
Q: Is there a limit to how much data I can send in one.send() call?
A: WebSockets can theoretically send massive payloads, but most servers configure a strict maximum frame size (e.g., 1MB or 2MB) to prevent Denial of Service (DoS) attacks. For large files, chunk them into smaller pieces.
17. Summary
In Chapter 6, we achieved true bidirectional communication. We usedsocket.send() to push data up to the server, and we set up an onmessage event listener to catch data coming down. By combining these two methods with some basic HTML and JavaScript, we created our very first real-time interactive interface.
18. Next Chapter Recommendation
We have looked closely atonopen and onmessage, but things don't always go perfectly on the web. Proceed to Chapter 7: WebSocket Events Explained, where we will complete our knowledge of the API by handling disconnections (onclose) and errors (onerror).