WebSockets under the hood with Node.js



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

let websocket;

function connect() {
    websocket = new WebSocket(wsUri);

    websocket.onopen = function (event) {
        outputDiv.innerHTML += "

Connected to server!

"; }; websocket.onmessage = function (event) { const receivedMessage = event.data; outputDiv.innerHTML += "

Received: " + receivedMessage + "

"; }; websocket.onerror = function (event) { outputDiv.innerHTML += "

Error: " + event.error + "

"; }; websocket.onclose = function (event) { outputDiv.innerHTML += "

Connection closed.

"; }; } sendButton.addEventListener("click", function () { const message = messageInput.value; if (websocket && websocket.readyState === WebSocket.OPEN) { websocket.send(message); messageInput.value = ""; } else { outputDiv.innerHTML += "

Error: Connection not open.

"; } }); connect(); // Connect immediately

This script sets up several event handlers using the browser-native API. We start up the WebSocket as soon as the script is loaded and watch for open, onclose, onmessage, and onerror events. Each one appends its updates to the DOM. The most important one is onmessage, where we accept the message from the server and display it.

The Click handler on the button itself takes the input typed in by the user (messageInput.value) and uses the WebSocket object to send it to the server with the send() function. Then we reset the value of the input to a blank string.

Assuming the back end is still running and available at ws://localhost:3000, we can now run the front end. We can use http-server as a simple way to run the front end. It’s a simple way to host static files in a web server, akin to Python’s http module or Java’s Simple Web Server, but for Node. It can be installed as a global NPM package or simply run with npx, from the client directory:

About WN

Check Also

Syria and the stakes for regional powers | Syria’s War

As Syria’s new leadership takes shape, competing media narratives in Iran and Turkiye illuminate the …

Advertisment ad adsense adlogger