Skip to main content
WebSockets Tutorial
CHAPTER 06 Beginner

Sending and Receiving Messages

Updated: May 14, 2026
15 min read

# 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 onmessage event listener to catch server responses.
  • Extract the payload data from a MessageEvent object.
  • 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 onmessage listener. 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, your onmessage listener catches their reply and adds it to the screen.
  • Stock Tickers: The client connects, and the server continuously fires messages to the client's onmessage listener 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

html
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Messaging</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-10">

    <div class="max-w-md mx-auto bg-white p-6 rounded shadow-md">
        <h1 class="text-xl font-bold mb-4">Echo Test</h1>
        
        <!-- Chat Display -->
        <div id="chat-box" class="h-48 bg-gray-50 border p-2 mb-4 overflow-y-scroll text-sm">
            <!-- Messages will appear here -->
        </div>

        <!-- Input Area -->
        <div class="flex gap-2">
            <input type="text" id="msg-input" class="border flex-1 p-2 rounded" placeholder="Type a message...">
            <button id="send-btn" class="bg-blue-500 text-white px-4 py-2 rounded">Send</button>
        </div>
    </div>

    <script>
        const socket = new WebSocket("wss://echo.websocket.events");
        const chatBox = document.getElementById("chat-box");
        const msgInput = document.getElementById("msg-input");
        const sendBtn = document.getElementById("send-btn");

        // Listen for messages FROM the server
        socket.onmessage = function(event) {
            // event.data contains the actual message string
            const serverMessage = event.data;
            
            // Append it to the chat box
            chatBox.innerHTML += `<div class="text-green-600 mb-1"><b>Server:</b> ${serverMessage}</div>`;
            // Auto-scroll to bottom
            chatBox.scrollTop = chatBox.scrollHeight;
        };

        // Send messages TO the server when button is clicked
        sendBtn.onclick = function() {
            const textToTransmit = msgInput.value;
            
            if (textToTransmit && socket.readyState === WebSocket.OPEN) {
                // Send over WebSocket
                socket.send(textToTransmit);
                
                // Show our own message in the UI
                chatBox.innerHTML += `<div class="text-blue-600 mb-1"><b>You:</b> ${textToTransmit}</div>`;
                msgInput.value = &#039;'; // Clear input
            } else {
                alert("Connection is not open yet!");
            }
        };
    </script>
</body>
</html>

8. The MessageEvent Object

When onmessage 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 use JSON.stringify to send, and JSON.parse to receive.
javascript
12345678
// Sending JSON
socket.send(JSON.stringify({ user: "Alice", text: "Hello!" }));

// Receiving JSON
socket.onmessage = function(event) {
    const dataObj = JSON.parse(event.data);
    console.log(dataObj.user + " says: " + dataObj.text);
};

10. Best Practices

  • Validate readyState: Always wrap your socket.send() in a check to ensure readyState === WebSocket.OPEN. If a user clicks "Send" while the connection is dropped, your app will crash.
  • Use Try/Catch for JSON: When parsing event.data using JSON.parse(), wrap it in a try...catch block. If the server accidentally sends plain text, JSON.parse will 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. 1. Run the code from Section 7.
  1. 2. Type "Hello Server" and hit Send.
  1. 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 the onmessage 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

Question 1

Which property of the onmessage event contains the actual message payload sent by the server?

Question 2

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 used socket.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 at onopen 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).

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