Categories
Web Development

WebSocket uses cases and how to implement them with minimal code

I recently built webhooktest.com, it’s a free service to view and inspect the data posted to a webhook URL by a third-party API or service. The website gives you a unique URL which you can use as a webhook and gives you another URL where you can view the data being posted to the webhook URL in real time.

Webhook URL – https://webhooktest.com/some-unique-code

View URL – https://webhooktest.com/some-unique-code/view

The view URL needs to be updated in real time whenever a request is received on the webhook URL. How can we achieve this? The webhook URL makes an entry into a database whenever it receives a request. How can it inform the view URL to fetch the new entry and display it?

One way to do is to have the view URL constantly check the database for any new entries. This is called polling. It is inefficient and resource consuming for obvious reasons. An efficient option is to have the webhook URL notify the view URL about a new request so it can fetch and display the new entry. This can be achieved using WebSocket.

WebSocket is a two way communication protocol and it is natively supported by all modern browsers.

WebSocket is capable of two way communication, so a client can send a message to a server and server can send a message to the client. In my case I just needed the server to intimate the client which in my case is the view page, about the new request that had come.

I have previously implemented WebSocket in ASP.Net, this time since I was working on a Linux server, I have implemented the same in NodeJS.

Whether you are using Node or ASP.Net or any other language, to implement WebSocket you need to handle 4 events – open, close, message and error. Events are same on both the client which is implemented in JavaScript and server which can be in your favorite server side programming language.

Implementing WebSocket server in ASP.Net

If you are working with IIS, you have to make sure WebSocket support is enabled under Turn Windows features on or off.

In .Net you have to implement the Microsoft.Web.WebSockets namespace. Following is the implementation of the WebSocket class in C#.

public class MyWebSocketHandler : WebSocketHandler
{
  public static WebSocketCollection clients = new WebSocketCollection();

  public override void OnOpen()
  {
    clients.Add(this);}

  public override void OnClose()
  {
    clients.Remove(this);
  }

  public override void OnMessage(string message)
  {
    clients.Broadcast(message);
  }

  public static void BroadcastMessage(string message) {
    clients.Broadcast(message);
  }
}

We are maintaining a collection of connected clients. We add to the collection when a new client joins, and we remove the client from the collection when it disconnects. When a message is received from the client, the OnMessage method is called. You can use the Broadcast method of the WebSocketCollection object to send a message to all clients. In the above class I have also created a static broadcast method to be called by external code to broadcast a message to all the connected clients.

Implementing WebSocket server in NodeJS

There are 2 popular packages in NodeJS that implement WebSocket – websocket and ws. I have used ws.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8000 });

wss.on('connection', function connection(ws) {
  ws.on('open', function() {
    console.log('new client connected');
  });

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.on('close', function() {
    console.log('a client disconnected');
  });
});

Client side implementation of WebSocket is also very easy.

var ws = new WebSocket("ws://websocket-url");

ws.onopen = function () {
  
}

ws.onmessage = function (e) {
  alert(e.data.toString());
}

ws.onclose = function () {
  
}

When a message is received from the server, the onmessage event is called and you can retrieve the message from the event object and handle it as per your business logic.

This is a very short primer on WebSocket. There are many more detailed tutorials available on WebSocket on the web. WebSocket are useful for building real time collaborative apps like live chat, collaborative editing applications like a white board or something like Google sheets. It can be used for one way messaging from server to client like updating prices, numbers or location on the client.