是否可以从Javascript ping服务器? [英] Is it possible to ping a server from Javascript?

查看:114
本文介绍了是否可以从Javascript ping服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个网络应用程序,要求我检查远程服务器是否在线。当我从命令行运行它时,我的页面加载时间达到了整整60秒(对于8个条目,它会随着更多的线性扩展)。

I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).

我决定去在用户端ping的路由。这样,我可以加载页面,让他们在浏览我的内容时等待服务器在线数据。

I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.

如果有人对上述问题有答案,或者如果他们知道一个解决方案来保持我的页面加载速度快,我一定会很感激。

If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.

推荐答案

我找到了一个人通过非常巧妙地使用本机 Image 对象来实现这一点。

I have found someone that accomplishes this with a very clever usage of the native Image object.

从它们的来源来看,这是主要功能(它依赖于源的其他部分,但你明白了。)

From their source, this is the main function (it has dependences on other parts of the source but you get the idea).

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);

  }
}

这适用于所有类型的服务器我测试过(网络服务器,ftp服务器和游戏服务器)。它也适用于端口。如果有人遇到失败的用例,请在评论中发帖,我会更新我的回答。

This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.

更新:上一个链接已被删除。如果有人发现或实施上述内容,请发表评论,我会将其添加到答案中。

Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.

更新2 :@trante足够好了提供一个jsFiddle。

Update 2: @trante was nice enough to provide a jsFiddle.

http://jsfiddle.net/GSSCD/203 /

更新3 :@Jonathon创建了一个带有实现的GitHub仓库。

Update 3: @Jonathon created a GitHub repo with the implementation.

https://github.com/jdfreder/pingjs

更新4 :看起来这个实现不再可靠。人们还报告说Chrome不再支持所有内容,因此抛出 net :: ERR_NAME_NOT_RESOLVED 错误。如果有人可以验证替代解决方案,我会将其作为接受的答案。

Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.

这篇关于是否可以从Javascript ping服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆