Polling vs. Long Polling vs. WebSocket vs. Server-Sent Events

There are several techniques for real-time communication between clients and servers. Each of these techniques has its own characteristics and use cases. Polling and long polling are simple to use but they aren’t as efficient as WebSocket and Server-Side Events. Here’s how these techniques compare and contrast against each other.

Polling

  • Polling involves a client sending requests to the server at regular intervals to check if there are any updates.
  • On receiving the request, the server responds with new data if one is available or an empty response if no data has been updated.
  • You can leverage simple AJAX requests and page reloads to implement polling in your applications.
  • Clients repeatedly request updates even when there are none, resulting in unnecessary network traffic and increased server load.
  • This approach is suitable for scenarios where updates are infrequent or a real-time response is not a priority.

Long Polling

  • Long polling reduces unnecessary requests to the server and enables near real-time updates compared to regular polling.
  • Servers hold requests open until an update is available rather than responding immediately to a client request.
  • The server responds when an update is available. Then, the client sends a new request to keep the connection alive.
  • When no updates are available within a particular timeframe, the server responds with an empty response. The client sends a new request and continues listening.
  • Although long polling reduces the frequency of requests and enables a real-time response, it still involves frequent connections and overhead due to request/response cycles.

WebSocket

  • WebSocket enables communication between servers and consumers over a single, persistent, reliable, and full-duplex connection.
  • WebSocket is ideally suited for applications requiring continuous data transfers, such as chat applications and collaboration tools.
  • Due to server-side infrastructure requirements, WebSocket isn’t supported in all legacy or restricted environments such as older browsers and certain network configurations.

Server-Sent Events

  • SSE provides a lightweight, unidirectional approach to server-client communication over HTTP.
  • Contrary to WebSockets, communication between server and client in server-sent events runs in only one direction, from server to client.
  • SSE enables real-time updates without the complexity of WebSockets.
  • SSE is well suited for scenarios where communication is unidirectional, i.e., the server needs to forward updates to clients, such as news feeds, notifications, or real-time monitoring dashboards.

Use Cases

WebSockets provide bidirectional communication between a server and a client, which makes them suitable for real-time polling apps, chat apps, etc. Server-Sent Events support a unidirectional communication between client and server. This means that the messages are transmitted in single direction only, i.e., from server to client. They are often used for push notifications, news feeds, and other similar purposes.

Read about implementing Server side events.. more here

Pivot a JavaScript Array: Convert a Column to a Row

Sometimes we need to convert a column to row in JavaScript array. It might be helpful to pass it as web service argument, generating chart dynamically or to display data in more meaningful way. In this post, we will create a method which converts a specified column to row in JavaScript array like below:

Consider the following array;

var arr = [
//["Product", "Year", "Sales"],
["Product 1", "2009", "1212"],
["Product 2", "2009", "522"],
["Product 1", "2010", "1337"],
["Product 2", "2011", "711"],
["Product 2", "2012", "2245"],
["Product 3", "2012", "1000"]
];

Use following method to convert this array;

function getPivotArray(dataArray, rowIndex, colIndex, dataIndex) {
        //Code from https://techbrij.com
        var result = {}, ret = [];
        var newCols = [];
        for (var i = 0; i < dataArray.length; i++) {
 
            if (!result[dataArray[i][rowIndex]]) {
                result[dataArray[i][rowIndex]] = {};
            }
            result[dataArray[i][rowIndex]][dataArray[i][colIndex]] = dataArray[i][dataIndex];
 
            //To get column names
            if (newCols.indexOf(dataArray[i][colIndex]) == -1) {
                newCols.push(dataArray[i][colIndex]);
            }
        }
 
        newCols.sort();
        var item = [];
 
        //Add Header Row
        item.push('Item');
        item.push.apply(item, newCols);
        ret.push(item);
 
        //Add content 
        for (var key in result) {
            item = [];
            item.push(key);
            for (var i = 0; i < newCols.length; i++) {
                item.push(result[key][newCols[i]] || "-");
            }
            ret.push(item);
        }
        return ret;
    }

In above method:
dataArray: Array to be converted
rowIndex: Index of column in array which is to be kept as first column
colIndex: Index of column whose values to be converted as columns in the output array.
dataIndex: Index of column whose values to be used as data (displayed in tabular/grid format).

The logic of method is simple. First it iterates the given array and create a result object of [rowIndex],[colIndex] = [dataIndex] format so that it can be fetched easily by using associative array like syntax. In the same iteration, we put unique values of colIndex in newCols array which will be used to create new columns. After this loop, we will get result object and newCols array. Now create a return array (ret), push newCols values for Header data and iterate result object, push values in ret object. Finally, ret variable will have the converted array.

Use this function to show HTML table;

function arrayToHTMLTable(myArray) {
           var result = "<table border='1' cellpadding='7' cellspacing='0'>";
           for (var i = 0; i < myArray.length; i++) {
               result += "<tr>";
               for (var j = 0; j < myArray[i].length; j++) {
                   result += "<td>" + myArray[i][j] + "</td>";
               }
               result += "</tr>";
           }
           result += "</table>";
 
           return result;
       }       

Add following on HTML side;

<h2>Original Array</h2>
   <div id="orgTable"></div>
 
   <h2>Converted Array</h2>
   <div id="pivotTable"></div>

jQuery to show the results;

$(function () {
          var output = getPivotArray(arr, 0, 1, 2);
          $('#orgTable').html(arrayToHTMLTable(arr));
          $('#pivotTable').html(arrayToHTMLTable(output));
      });

Reference

https://www.cnblogs.com/vvull/p/14744863.html

https://medium.com/@saravanan16498/pivot-and-group-data-sk-yazhini9798-4a63e5cc3dd3