-2

I mean what technique is used to send and receive data between the client and the server? How does it achieve near-realtime results when changes occur.

Can someone show me the code that is used?

Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28

2 Answers2

4

StackOverflow uses websockets to keep an open connection between the client and the server from which data can be passed from the server to the client. This is often preferable to AJAX polling in that data is pushed to the client rather than having to be polled for and pulled via AJAX requests. Most likely SO falls back to the old AJAX polling method for older browsers that do not have support for web sockets

SO networks tab screenshot

From this pusher.com article:

WebSockets represent a long awaited evolution in client/server web technology. They allow a long-held single TCP socket connection to be established between the client and server which allows for bi-directional, full duplex, messages to be instantly distributed with little overhead resulting in a very low latency connection.

This SO post nicely explains the pros and cons of different client-server communication methods




The actual code looks something like this:

StackExchange.realtime = function() {
  function Socket(options) {
    var array = options.split(",");
    var length = array.length;
    var i = index % length;
    var url = array[i];
    if (null != url && (0 != url.indexOf("ws://") && (0 != url.indexOf("wss://") && (url = ("https:" === document.location.protocol ? "wss://" : "ws://") + url))), "WebSocket" in window || "MozWebSocket" in window) {
      if (self) {
        try {
          publish("closing WebSocket");
          self.close();
        } catch (c) {
        }
      }
      if (!self) {
        try {
          self = "WebSocket" in window ? new WebSocket(url) : new MozWebSocket(url);
        } catch (ex) {
          return publish("Sockets disabled - " + ex.message), void 0;
        }
        self.onopen = function() {
          if (!U) {
            U = true;
          }
          index = 0;
          publish("WebSocket opened");
          f();
          handle();
          setInterval(done, 6E4);
        };
        self.onmessage = function(msg) {
          var self = $.parseJSON(msg.data);
          mockPlugin.emitEvent(self.action, [self.data]);
        };
        self.onclose = function() {
          self = null;
          publish("WebSocket closed");
          if (5 > index) {
            if (D > 0) {
              index++;
              D--;
              publish("reconnect attempt:" + index + " max retries:" + D);
              setTimeout(function() {
                StackExchange.realtime.init(options);
              }, (new Date).getTime() % 50 / 20 * 1E3);
            }
          }
        };
        self.onerror = function() {
          publish("WebSocket failed");
          self = null;
        };
      }
    }
  }
  function f() {
    if (null != self && 1 == self.readyState) {
      var i = 0;
      var l = elems.length;
      for (;l > i;i++) {
        publish("sending " + elems[i]);
        self.send(elems[i]);
      }
    }
  }
  function publish(topic) {
    if (StackExchange.options.enableLogging) {
      console.log("realtime: " + topic);
    }
  }
  function handle() {
    mockPlugin.addListener("hb", function(str) {
      self.send(str);
    });
  }
  function next(elm) {
    elems.push(elm);
    f();
  }
  function callback(i) {
    publish("unsubscribing " + i);
    var position = $.inArray(i, elems);
    if (-1 != position) {
      elems.splice(position, 1);
      if (null != self) {
        if (1 == self.readyState) {
          self.send("-" + i);
        }
      }
    }
  }

and is called with:

StackExchange.ready(function () {
    StackExchange.realtime.init('wss://qa.sockets.stackexchange.com,ws://qa.sockets.stackexchange.com');
    StackExchange.realtime.subscribeToInboxNotifications();
    StackExchange.realtime.subscribeToReputationNotifications('1');
    StackExchange.realtime.subscribeToTopBarNotifications('1');
});
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28
0

Usually, using some form of AJAX.

AJAX refers to the group of technologies that allows only a portion of a page to update. Typically, it involves JavaScript (and often jQuery) to make a call to a web service, which returns the the requested data (and optionally updates data). The client script then displays the data as needed.

There are many variations on this, although many are just higher level abstractions build around some sort of web services.

Examples of doing this are outside the scope of a stackoverflow answer. But there are many examples on the web. You can see an example using WebForms and jQuery in the article Calling Web Services Using AJAX.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466