3.7 C
New York
Friday, November 22, 2024

WebSockets below the hood with Node.js




// script.js
const wsUri = "ws://localhost:3000";
const outputDiv = doc.getElementById("output");
const messageInput = doc.getElementById("message");
const sendButton = doc.getElementById("send-btn");

let websocket;

operate join() {
    websocket = new WebSocket(wsUri);

    websocket.onopen = operate (occasion) {
        outputDiv.innerHTML += "

Linked to server!

"; }; websocket.onmessage = operate (occasion) { const receivedMessage = occasion.information; outputDiv.innerHTML += "

Obtained: " + receivedMessage + "

"; }; websocket.onerror = operate (occasion) { outputDiv.innerHTML += "

Error: " + occasion.error + "

"; }; websocket.onclose = operate (occasion) { outputDiv.innerHTML += "

Connection closed.

"; }; } sendButton.addEventListener("click on", operate () { const message = messageInput.worth; if (websocket && websocket.readyState === WebSocket.OPEN) { websocket.ship(message); messageInput.worth = ""; } else { outputDiv.innerHTML += "

Error: Connection not open.

"; } }); join(); // Join instantly

This script configures a number of occasion handlers utilizing the browser’s native API. We begin the WebSocket as quickly because the script hundreds and observe open, onclose, onmessageand onerror occasions. Every one provides its updates to the DOM. Crucial one is onmessagethe place we settle for the message from the server and show it.

The Button Click on handler takes the enter entered by the person (messageInput.worth) and makes use of the WebSocket object to ship it to the server with the ship() operate. We then reset the worth of the enter to a clean string.

Assuming the backend continues to be operating and obtainable on ws://localhost:3000now we will run the front-end. we will use http server as a easy method to run the interface. It’s a easy method to host static information on an online server, much like Python’s http module or Easy Java Internet Serverhowever for Node. It may be put in as a world NPM package deal or just run with npxfrom the consumer listing:

Related Articles

Latest Articles