3 options you can use to handle streamed data

An article about WebSockets and other alternatives like long pooling and observables, used for streamed and bi-directional data

websocket

Introduction to Websocket and it's alternatives

Today we have chats messengers, social media apps, and one thing they all have in common is streamed real-time data, but how do they solve this problem? Well, some use long pooling, others observables these approaches tend to overwhelm the use of HTTP it isn't the best solution and has its own drawbacks, but in 2009 chrome was already giving full support for WebSockets and you might be asking what is WebSockets? Websocket is defined as a protocol which provides full-duplex communication channels over a single TCP. Here I will show some examples of how to use each one.

My purpose will be giving you more hands-on solutions, I will provide some theoretical links if you feel in need to understand more the principles behind each one.

Websocket

The code bellow I got from JavaScript Info, it's an example of how to use websocket,

Once is created we can listen to four events: open, message, error and close. They are very self-explanatory haha

// first we create the connection, the url uses the protocol wss://
let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");

socket.onopen = function(e) {
  alert("[open] Connection established");
  alert("Sending to server");
  socket.send("My name is Pedro");
};

socket.onmessage = function(event) {
  alert(`[message] Data received from server: ${event.data}`);
};

socket.onclose = function(event) {
  if (event.wasClean) {
    alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
  } else {
    // e.g. server process killed or network down
    // event.code is usually 1006 in this case
    alert('[close] Connection died');
  }
};

socket.onerror = function(error) {
  alert(`[error] ${error.message}`);
};

Long Pooling

An example of long pooling basically it's a normal ajax method but will be triggered from time to time or will be listening to file changes in the server and call the method again.

function pollTask() { 

    $.ajax({

        url: '/api/Polling',
        async: true,            // by default, it's async, but...
        dataType: 'json',       // or the dataType you are working with
        timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
        cache: false

    }).done(function (eventList) {  

       // Handle your data here
       var data;
       for (var eventName in eventList) {

            data = eventList[eventName];
            dispatcher.handle(eventName, data); // handle the `eventName` with `data`

       }

    }).always(pollTask);

}

Rxjs Observables

The last alternative is using observables, what happens here we create an observable with a 1-second interval, we use flatMap to mapping the returned data and retrieve in the way we want to subscribe, fromPromise will get this data from an URL, but you could use in other situations, I will recommend this link if you need to use from a file or some other situation, different from an API.

Observables examples

 Rx.Observable.interval(1000)
  .flatMap(function(i) {
    return Rx.Observable.fromPromise($.getJSON("get_data", //ENDPOINT
        function (data) {
          return data;
        }));
  });
  
  obs.subscribe((value) => {
  console.log(value);
  });

Well if you still want to know more I strongly recommend this youtube video A Beginner's Guide to WebSockets

Comments