13.9 C
New York
Wednesday, October 9, 2024

WebSockets beneath 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 units up a number of occasion handlers utilizing the browser-native API. We begin up the WebSocket as quickly because the script is loaded and look ahead to open, onclose, onmessage, and onerror occasions. Every one appends its updates to the DOM. Crucial one is onmessage, the place we settle for the message from the server and show it.

The Click on handler on the button itself takes the enter typed in by the person (messageInput.worth) and makes use of the WebSocket object to ship it to the server with the ship() operate. Then we reset the worth of the enter to a clean string.

Assuming the again finish remains to be working and out there at ws://localhost:3000, we will now run the entrance finish. We are able to use http-server as a easy method to run the entrance finish. It’s a easy method to host static information in an online server, akin to Python’s http module or Java’s Easy Internet Server, however for Node. It may be put in as a worldwide NPM package deal or just run with npx, from the consumer listing:



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles