📜  wiki BackendPolling (1)

📅  最后修改于: 2023-12-03 15:35:41.488000             🧑  作者: Mango

BackendPolling Wiki Introduction

Description

BackendPolling is a feature in software development that allows the client-side applications to retrieve new data from the server-side at specific intervals. This technique is used in various types of applications that require real-time data updates, such as chat applications or stock market dashboards.

The BackendPolling technique works by having the client-side application send a request to the server-side at a set interval, asking for new data to be sent back. The interval can be set by the developer and can vary depending on the use case. Once the server-side receives the request, it checks for new data and sends it back to the client-side if any is found.

Implementation

BackendPolling can be implemented using AJAX or WebSocket. AJAX is a commonly used technique, where the client server makes a request to the server and awaits its response. WebSocket is another option and works by creating a persistent connection between the client and the server, allowing data to be sent bidirectionally.

AJAX Implementation
function fetchData() {
  // Make request to server using AJAX
  $.ajax({
    type: "GET",
    url: "/api/data",
    dataType: "json",
    success: function(response) {
      // Handle response from server
      displayData(response);
    },
    error: function(xhr, status, error) {
      // Handle error from server
      console.log(error);
    },
    complete: function() {
      // Start the polling loop again after request is complete
      setTimeout(fetchData, 5000);
    }
  });
}

// Start the polling loop
fetchData();
WebSocket Implementation
// Create new WebSocket connection
var socket = new WebSocket("wss://example.com/ws");

// Handle WebSocket connection opening
socket.onopen = function() {
  console.log("Connected to WebSocket server");

  // Send a message to the server
  socket.send("Hello Server!");
};

// Handle WebSocket message receiving
socket.onmessage = function(event) {
  console.log("Message received from server:", event.data);

  // Handle message from server
  displayData(event.data);
};

// Handle WebSocket connection closing
socket.onclose = function() {
  console.log("Disconnected from WebSocket server");

  // Try to reconnect after a short period of time
  setTimeout(function() {
    socket = new WebSocket("wss://example.com/ws");
  }, 5000);
};
Conclusion

BackendPolling is a useful technique for real-time data updates in web applications. It can be implemented using various techniques, such as AJAX or WebSocket. By allowing the client-side application to retrieve new data from the server-side at specific intervals, it ensures that the user always has access to the latest information.