How to show ping output dynamically in a web page?

前端 未结 2 505
有刺的猬
有刺的猬 2021-02-06 03:50

As part of a diagnostics page I would like to have the user be able to run a \"ping\", ie an ordinary shell command to send ICMP_ECHO_REQUSTs to a certain IP and display the res

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 04:33

    From what it sounds, you only need the ping when the page is loaded and people are watching it. If that is the case, I think you can avoid a backend process.

    I would think that an ajax call to a controller action that pings and then outputs the response. You could control the frequency, start, stop through javascript on the page and update a specific div or other page object with the response.

    this example uses ruby ping library which only returns true. If you need more functionality there are other libraries available (e.g. net-ping).

    In your controller

    require 'ping'
    
    def ping
      if Ping.ping_echo(params[:hostname], params[:timeout])
        render :text => "Oh goodie, it pinged successfully"
      else
        render :text => "No go on the pingage"
      end
    end
    

    And then in your javascript (I am using jQuery, but you could use prototype/scriptaculous or you favorite JS flavor):

    function ping_host {
      $.get("/controller/ping", function(data){
        $("#some_div_id").append(data);
      });
    }
    

    From there you can use a setTimeout command to run it every 5 seconds or however often you would like to generate the ping.

    If you need the ping going on all the time, you might want to look at some backend job processors like resqueue that would update a database table with the ping results, or a memcached store that you then poll using a similar method as above from the page.

提交回复
热议问题