Home >Web Front-end >JS Tutorial >Can JavaScript Ping a Server, and How Reliable Is This Method?

Can JavaScript Ping a Server, and How Reliable Is This Method?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 07:58:12898browse

Can JavaScript Ping a Server, and How Reliable Is This Method?

Can Javascript Ping a Server?

In the endeavor to monitor server availability, a developer encountered a dilemma where page loading time soared to 60 seconds for just eight servers. Seeking a solution, they pondered the possibility of pinging servers from the client-side via JavaScript.

Fortunately, a resourceful individual shared a clever technique using the Image object. This function initiates a ping:

function Pinger_ping(ip, callback) {

  if(!this.inUse) {

    this.inUse = true;
    this.callback = callback
    this.ip = ip;

    var _that = this;

    this.img = new Image();

    this.img.onload = function() {_that.good();};
    this.img.onerror = function() {_that.good();};

    this.start = new Date().getTime();
    this.img.src = "http://" + ip;
    this.timer = setTimeout(function() { _that.bad();}, 1500);

  }
}

This approach relies on the Image object to check server availability. The mechanism proved effective for various server types and ports. However, its reliability has reportedly diminished, and Chrome may no longer support it, resulting in an error.

The above is the detailed content of Can JavaScript Ping a Server, and How Reliable Is This Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn