Sitemap
CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Create WebSocket Playground

5 min readDec 27, 2021

--

As a beginner, the WebSocket was an enigma for me.

I just need to set it up once! A tunel!?

While getting started I found many resources which talk about the WHAT are WebSockets, HOW are they used, and WHERE/WHEN they should be used. But I wanted to use it, run it — a quick & dirty setup. I wanted to check different conditions, especially their behaviour when the browsers lose connectivity. (In case you are wondering the web sockets on Chrome and Firefox behaves differently when the connection is lost. No surprise there!)

This blog is a quick guide to set up WebSockets and experiment with them. But to begin with just a quick introduction to WebSockets.

The 3 W’s — What, Why & Who

WebSockets are used to open an interactive & persistent channel between the client (browsers) and the server. The client establishes and closes the connection as per its need. The WebSockets can be designed to support the unidirectional or bidirectional flow of communication.

Press enter or click to view image in full size
Unidirectional or bidirectional flow of communication with WebSockets.

We can identify these protocols on many websites. Consider the StackOverflow. If you spend enough time on this site you can see the WebSockets in play. The new activities are sent through a WebSocket connection to the client.

Press enter or click to view image in full size
Stackoverflow’s horrible imitation using draw.io — Web Sockets In Real-time.

To view the WebSocket requests on any website you can —

  1. Open Developer Tools in the browser.
  2. Switch to the Network tab.
  3. Filter the ws requests.
  4. Select the ws request and check the Messages tab for ongoing communications.
Press enter or click to view image in full size
Identifying WebSockets Requests in Developer Tools.

As you might have guessed by now WebSockets are a joint venture for clients and servers. The following links provide detailed setups and tools required.

  1. The WebSocket API (WebSockets)
  2. Writing WebSocket client applications
  3. Writing WebSocket servers

Or you can take the pick from The WebSockets Tools.

But if you just need a quick setup and like me, you are only familiar with JavaScript continue reading.

A WebSocket Playground

In the playground, we will achieve the most basic implementation of the server-client WebSocket connection as shown in the following image.

Press enter or click to view image in full size
A Little Requirement

We will establish the WebSocket connection, pass some messages and then close the connection from the client.

Setting up the project

We will set up a NodeJS development environment (which is quick and easy). If you are new and need more details on how to set up a NodeJS project check Set Up and Run a Simple Node Server Project and Express web framework (Node.js/JavaScript). You can ignore the Express part if not required. We will be only using NodeJS.

Get Darshna Rekha’s stories in your inbox

Join Medium for free to get updates from this writer.

Our project structure will include only two files — client.js and server.js.

- ws_starter
| - client.js
| - server.js
| - package.json

We are going to use a NodeJS Web Socket library — ws.

Setting up the server

Press enter or click to view image in full size
What will the Server do?

Once the client requests the connection to the server, the server can send messages to the client or listen to the message coming from the client.

// server.jsconst WebSocket = require("ws");// Create a web socket connection at port 8080.
// This is where the client will keep listening to.
const wss = new WebSocket.Server({ port: 8080 });
wss.on("connection", (ws) => {
ws.send("SERVER: Connection established");
function pingClient() {
ws.send("SERVER: PING");
}
// Keep pinging the client every 4 seconds.
const ping = setInterval(pingClient, 4000);
// Listen to the message coming from client.
ws.on("message", (message) => {
console.log(`${new Date().toLocaleTimeString()}: ${message}`);
});
// Clearing up when client closes web socket connection
ws.on("close", () => {
clearInterval(ping);
console.log("Connection closed.");
});
});

This is all that is required and now we will start the server. Open the terminal for the root of your project and run the Node server.

node server

The WebSocket server is running at localhost:8080.

Setting up the Client

Press enter or click to view image in full size
What will the Client do?

The client will establish the connection with the WebSocket server and then send an initial message as soon as the connection is open. There is an onerror event for handling errors such as network error, or the client missing any incoming message from the server. After 10 seconds the WebSocket connection is closed.

// client.jsconst WebSocket = require("ws");
const url = "ws://localhost:8080";
const connection = new WebSocket(url);
let introduceStop;connection.onopen = () => {
// After connection opens send message to server.
connection.send("CLIENT: PONG");
// After 10 seconds close web socket connection.
introduceStop = setTimeout(function () {
console.log(
`${new Date().toLocaleTimeString()}: Client closing WebSocket connection`
);
connection.close();
}, 10000);
};
// Catch error while web socket connection is open.
// After `onerror`, `onclose` will be triggered.
connection.onerror = (error) => {
console.log(`Web socket error: ${error}`);
};
// Keep reading messages from server.
connection.onmessage = (event) => {
console.log(`${new Date().toLocaleTimeString()} ${event.data}`);
};
// Clear things once web socket connection is closed.
connection.onclose = () => {
clearTimeout(introduceStop);
console.log("Web Socket connection properly closed.");
};

For the client, you can either use your project or run the following in the terminal.

node client

Now with both client and server up and running, we can proceed to the terminals.

Testing the WebSocket Playground

We have two terminals fired up for server and client respectively. If we have them opened in the split window we can see the following behaviour.

Press enter or click to view image in full size
WebSocket Playground in Motion | Made using Canva |

That is all we need for the playground. We have a server that we can modify to send any data or implement more features. We do not need to keep the client in the same place. We only need to establish the WebSocket connection and keep the server alive.

The code for the above setup is available at darshna09/websocket_mindmapping.

References

  1. Express web framework (Node.js/JavaScript) | MDN
  2. Node.js server without a framework | Level Up Coding | Medium

--

--

Darshna Rekha
Darshna Rekha

Written by Darshna Rekha

💼 Software Engineer at Cisco Systems, Inc. 🎯 Learn - Code - Repeat 📚 If I am not coding, I am reading

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers