Creating a WebSocket Client with JavaScript

Overview

In this chapter, we will create a simple WebSocket client using JavaScript. The client will connect to the WebSocket server we created in the previous chapter, send messages, and display received messages in the browser.

Setting Up the HTML Structure

First, we'll create an HTML file that will serve as the user interface for our WebSocket client. The HTML will include a button to connect to the WebSocket server, a text input for sending messages, and a div to display received messages.

Step 1: Create the HTML File

Create a new file named index.html and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 800px;
            margin: auto;
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #333;
        }
        #messages {
            margin-top: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            background: #f9f9f9;
            height: 200px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket Client</h1>
        <button id="connect">Connect</button>
        <input type="text" id="messageInput" placeholder="Type a message...">
        <button id="send">Send</button>
        <div id="messages"></div>
    </div>

    <script src="app.js"></script>
</body>
</html>

This HTML file includes:

  • A button to connect to the WebSocket server.
  • A text input to type messages.
  • A button to send messages.
  • A div to display received messages.
  • A link to an external JavaScript file app.js, which will contain our WebSocket client logic.

Implementing the WebSocket Client

Next, we'll implement the WebSocket client logic in app.js. The client will connect to the WebSocket server, handle various WebSocket events, and send and receive messages.

Step 2: Create the JavaScript File

Create a new file named app.js and add the following code:

let socket;

document.getElementById('connect').addEventListener('click', () => {
    socket = new WebSocket('ws://localhost:8000/ws');
    
    socket.addEventListener('open', (event) => {
        console.log('Connected to WebSocket server.');
        document.getElementById('messages').innerHTML += '<p>Connected to WebSocket server.</p>';
    });
    
    socket.addEventListener('message', (event) => {
        console.log('Message from server ', event.data);
        document.getElementById('messages').innerHTML += '<p>' + event.data + '</p>';
    });
    
    socket.addEventListener('error', (event) => {
        console.error('WebSocket error: ', event);
        document.getElementById('messages').innerHTML += '<p>WebSocket error: ' + event + '</p>';
    });
    
    socket.addEventListener('close', (event) => {
        console.log('WebSocket closed: ', event);
        document.getElementById('messages').innerHTML += '<p>WebSocket closed.</p>';
    });
});

document.getElementById('send').addEventListener('click', () => {
    const message = document.getElementById('messageInput').value;
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(message);
        document.getElementById('messageInput').value = '';
    }
});

Let's break down this code:

  • We define a variable socket to hold the WebSocket instance.
  • We add an event listener to the "Connect" button. When clicked, it creates a new WebSocket connection to the server at ws://localhost:8000/ws.
  • We add event listeners for the WebSocket events open, message, error, and close to handle connection status, incoming messages, errors, and connection closures.
  • We add an event listener to the "Send" button. When clicked, it sends the message typed in the input field to the WebSocket server if the connection is open.

Running the Client

With the server running (from Chapter 2) and the client set up, open index.html in your browser. Click "Connect" to establish a WebSocket connection, type a message in the input field, and click "Send" to send the message to the server. Messages sent and received will be displayed in the messages div.

Conclusion

In this chapter, we created a simple WebSocket client using JavaScript that connects to our FastAPI WebSocket server. This client can send and receive messages in real-time, providing a foundation for more complex interactions.

In the next chapter, we will explore handling various WebSocket events and managing the connection lifecycle effectively.

Comments

Leave a Reply