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.
<!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.
- 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.
- onopen (the connection is established)
- 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!".
- onmessage (a message is received)
The JavaScript logic
Initializing the WebSocket connection
window.onload = function () { echo_service = new WebSocket("ws://127.0.0.1:8080/chat"); ... };
Handling WebSocket events
The WebSocket client has four main event handlers:
if (url.pathname === "/") return new Response(Bun.file("./index.html"));
<!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.
The JavaScript logic
Initializing the WebSocket connection
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.
- 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.
- 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.
- When the page loads, the browser establishes a WebSocket connection with the server.
- Upon successful connection, a message is logged saying, "? Connected to WebSocket!".
- Users can type a message in the input box and click the "Submit" button. The message is sent to the WebSocket server.
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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/)...

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.

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

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. �...
