Home Web Front-end JS Tutorial WebSocket Client with JavaScript

WebSocket Client with JavaScript

Dec 03, 2024 am 12:33 AM

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"));
Copy after login
Copy after login

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>



<h2>
  
  
  Explaining the client code
</h2>

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


<hr>

<h3>
  
  
  The HTML structure
</h3>



<pre class="brush:php;toolbar:false"><!doctype html>
<html>
    <head>
        <title>WebSocket with Bun and JavaScript</title>
    </head>
    <body>
        <main>



<ul>
<li>The input field (<input>
<li>The submit button (<input type="button">): when clicked, it triggers the sendMessage(event) function to send the typed message to the server.
Copy after login
  • The messages/events log (

      The JavaScript logic

      Initializing the WebSocket connection

      window.onload = function () {
          echo_service = new WebSocket("ws://127.0.0.1:8080/chat");
          ...
      };
      
      Copy after login
      Copy after login
      • 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)
        if (url.pathname === "/") 
          return new Response(Bun.file("./index.html"));
      
      Copy after login
      Copy after login
      • 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)
      <!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>
      
      
      
      <h2>
        
        
        Explaining the client code
      </h2>
      
      <p>This code creates a simple <strong>WebSocket client</strong> in a browser to interact with a WebSocket server. Here's a detailed explanation of its components:</p>
      
      
      <hr>
      
      <h3>
        
        
        The HTML structure
      </h3>
      
      
      
      <pre class="brush:php;toolbar:false"><!doctype html>
      <html>
          <head>
              <title>WebSocket with Bun and JavaScript</title>
          </head>
          <body>
              <main>
      
      
      
      <ul>
      <li>The input field (<input>
      <li>The submit button (<input type="button">): when clicked, it triggers the sendMessage(event) function to send the typed message to the server.
      Copy after login
    • The messages/events log (

      The JavaScript logic

      Initializing the WebSocket connection

      window.onload = function () {
          echo_service = new WebSocket("ws://127.0.0.1:8080/chat");
          ...
      };
      
      Copy after login
      Copy after login
      • 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.onopen = function () {
             append("? Connected to WebSocket!");
         };
      
      Copy after login
      • 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.onmessage = function (event) {
             append(event.data);
         };
      
      Copy after login
      • 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

         echo_service.onclose = function () {
             append("Connection closed");
         };
      
      Copy after login
      • 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

         echo_service.onerror = function () {
             append("Error happens");
         };
      
      Copy after login
      • This utility function adds WebSocket events and messages to the

          list (id="websocket_events").
        • insertAdjacentHTML("beforeend", "

        • " text ";
        • "): inserts the given text as a new list item (
        • ) at the end of the list.


        • Styling with PicoCSS

          function sendMessage(event) {
              let message = document.getElementById("message").value;
              echo_service.send(message);
          }
          
          Copy after login

          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!

          The above is the detailed content of WebSocket Client with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

  • Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

    Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

    Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

    There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

    Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

    JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

    How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

    How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

    How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

    Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

    Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

    Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

    How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

    Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

    The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

    In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

    See all articles