DEV Community

Cover image for WebSocket Client with JavaScript
Roberto B.
Roberto B.

Posted on

5

WebSocket Client with JavaScript

In the previous article of this series, "WebSocket with JavaScript and Bun", we explored how to initialize a server capable of handling both HTTP requests and WebSocket connections.

We defined a rule for HTTP requests to serve the index.html file when a request is made to /. The index.html file contains the client-side logic for establishing a connection with the WebSocket server and sending messages as a client.

The client code

In the fetch method of the server explained in "WebSocket with JavaScript and Bun" is implemented this code:

  if (url.pathname === "/") 
    return new Response(Bun.file("./index.html"));
Enter fullscreen mode Exit fullscreen mode

This means that when a browser request is made to http://localhost:8080/, the content of the index.html file is sent to the browser.
The HTML will render a simple form with input text and a button and ship the logic for connecting to the WebSocket server as a client.

<!doctype html>
<html>
    <head>
        <title>WebSocket with Bun and JavaScript</title>
        <script>
            let echo_service;
            append = function (text) {
                document
                    .getElementById("websocket_events")
                    .insertAdjacentHTML("beforeend", "<li>" + text + ";</li>");
            };
            window.onload = function () {
                echo_service = new WebSocket("ws://127.0.0.1:8080/chat");
                echo_service.onmessage = function (event) {
                    append(event.data);
                };
                echo_service.onopen = function () {
                    append("πŸš€ Connected to WebSocket!");
                };
                echo_service.onclose = function () {
                    append("Connection closed");
                };
                echo_service.onerror = function () {
                    append("Error happens");
                };
            };

            function sendMessage(event) {
                console.log(event);
                let message = document.getElementById("message").value;
                echo_service.send(message);
            }
        </script>
        <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"
        />
    </head>

    <body>
        <main class="container">
            Message: <input value="Hello!" type="text" id="message" />
            <input
                type="button"
                value="Submit"
                onclick="sendMessage(event)"
            /><br />
            <ul id="websocket_events"></ul>
        </main>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explaining the client code

This code creates a simple WebSocket client in a browser to interact with a WebSocket server. Here's a detailed explanation of its components:


The HTML structure

<!doctype html>
<html>
    <head>
        <title>WebSocket with Bun and JavaScript</title>
    </head>
    <body>
        <main class="container">
            Message: <input value="Hello!" type="text" id="message" />
            <input
                type="button"
                value="Submit"
                onclick="sendMessage(event)"
            /><br />
            <ul id="websocket_events"></ul>
        </main>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • The input field (<input id="message">): a text box where users can type a message to send via the WebSocket.
  • The submit button (<input type="button">): when clicked, it triggers the sendMessage(event) function to send the typed message to the server.
  • The messages/events log (<ul id="websocket_events">): displays all WebSocket-related events (e.g., connection status, received messages).

The JavaScript logic

Initializing the WebSocket connection

window.onload = function () {
    echo_service = new WebSocket("ws://127.0.0.1:8080/chat");
    ...
};
Enter fullscreen mode Exit fullscreen mode
  • WebSocket("ws://127.0.0.1:8080/chat"): creates a new WebSocket connection to the server at 127.0.0.1 on port 8080, specifically the /chat endpoint.
  • The variable echo_service holds the WebSocket instance, which facilitates communication with the server.

Handling WebSocket events

The WebSocket client has four main event handlers:

  1. onopen (the connection is established)
   echo_service.onopen = function () {
       append("πŸš€ Connected to WebSocket!");
   };
Enter fullscreen mode Exit fullscreen mode
  • The onopen function is triggered when the connection to the server is successfully established.
  • It appends a message to the log saying, "πŸš€ Connected to WebSocket!".
  1. onmessage (a message is received)
   echo_service.onmessage = function (event) {
       append(event.data);
   };
Enter fullscreen mode Exit fullscreen mode
  • The onmessage function is triggered whenever a message is received from the server.
  • The server’s message (event.data) is appended to the event log using the append function.
  1. onclose (the connection is closed)
   echo_service.onclose = function () {
       append("Connection closed");
   };
Enter fullscreen mode Exit fullscreen mode
  • The onclose function is triggered when the connection to the server is closed (e.g., the server disconnects).
  • The function appends "Connection closed" to the event log.
  1. onerror (an error is occurred)
   echo_service.onerror = function () {
       append("Error happens");
   };
Enter fullscreen mode Exit fullscreen mode
  • The onerror function is triggered when an error occurs during communication.
  • The function logs "Error happens" to indicate the issue.

Sending messages to the server

function sendMessage(event) {
    let message = document.getElementById("message").value;
    echo_service.send(message);
}
Enter fullscreen mode Exit fullscreen mode
  • The sendMessage function is called when the "Submit" button is clicked.
  • document.getElementById("message").value: it retrieves the text entered by the user in the input box.
  • echo_service.send(message): it sends the user’s message to the WebSocket server.

Logging events

append = function (text) {
    document
        .getElementById("websocket_events")
        .insertAdjacentHTML("beforeend", "<li>" + text + ";</li>");
};
Enter fullscreen mode Exit fullscreen mode
  • This utility function adds WebSocket events and messages to the <ul> list (id="websocket_events").

  • insertAdjacentHTML("beforeend", "<li>" + text + ";</li>"): inserts the given text as a new list item (<li>) at the end of the list.


Styling with PicoCSS

<link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"
/>
Enter fullscreen mode Exit fullscreen mode

PicoCSS provides a lightweight and elegant styling for the page, ensuring the form and event log look polished without additional custom CSS.


The recap, how it works

  1. When the page loads, the browser establishes a WebSocket connection with the server.
  2. Upon successful connection, a message is logged saying, "πŸš€ Connected to WebSocket!".
  3. Users can type a message in the input box and click the "Submit" button. The message is sent to the WebSocket server.

Next Steps

This article explored how to implement a WebSocket client to communicate with a WebSocket server. In the previous article of this series, we focused on structuring a basic WebSocket server.

In the next article, we will explore WebSocket functionality further by implementing broadcasting logic. This feature allows messages from one client to be forwarded to all connected clients, making it essential for building real-time applications like chat systems, collaborative tools, or live notifications.

Stay tuned!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay