search
HomeWeb Front-endJS TutorialWebSocket Client with JavaScript

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"));

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.


    
        <title>WebSocket with Bun and JavaScript</title>
        <script>
            let echo_service;
            append = function (text) {
                document
                    .getElementById("websocket_events")
                    .insertAdjacentHTML("beforeend", "<li>" + text + ";");
            };
            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">
    

    
        <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">

    
        <title>WebSocket with Bun and JavaScript</title>
    
    
        <main>



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


<hr>

<h3>
  
  
  The JavaScript logic
</h3>

<h4>
  
  
  Initializing the WebSocket connection
</h4>



<pre class="brush:php;toolbar:false">window.onload = function () {
    echo_service = new WebSocket("ws://127.0.0.1:8080/chat");
    ...
};
  • 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"));
  • 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)

    
        <title>WebSocket with Bun and JavaScript</title>
        <script>
            let echo_service;
            append = function (text) {
                document
                    .getElementById("websocket_events")
                    .insertAdjacentHTML("beforeend", "<li>" + text + ";</script>
"); }; 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); }

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


    
        <title>WebSocket with Bun and JavaScript</title>
    
    
        <main>



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


<hr>

<h3>
  
  
  The JavaScript logic
</h3>

<h4>
  
  
  Initializing the WebSocket connection
</h4>



<pre class="brush:php;toolbar:false">window.onload = function () {
    echo_service = new WebSocket("ws://127.0.0.1:8080/chat");
    ...
};
  • 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!");
   };
  • 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);
   };
  • 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");
   };
  • 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");
   };
  • 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);
}

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
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
Related Article
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function