Home >Web Front-end >JS Tutorial >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.
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.
window.onload = function () { echo_service = new WebSocket("ws://127.0.0.1:8080/chat"); ... };
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.
window.onload = function () { echo_service = new WebSocket("ws://127.0.0.1:8080/chat"); ... };
echo_service.onopen = function () { append("? Connected to WebSocket!"); };
echo_service.onmessage = function (event) { append(event.data); };
echo_service.onclose = function () { append("Connection closed"); };
echo_service.onerror = function () { append("Error happens"); };
This utility function adds WebSocket events and messages to the
insertAdjacentHTML("beforeend", "
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.
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!