正常情况下,其它浏览器能够自动检测是否具有网络链接,但是 google 浏览器在这个方面有 BUG,很多网站采用的一种做法是不断的向服务器发送请求,确保连接的稳定,如果连不上了,就说明网络断开了,所以你的问题就可以采用类似的办法,下面是 js 代码:
function isOnline(){
var img = new Image()
img.id = "test_is_online"
img.onload = function(){
document.body.removeChild(
document.getElementById("test_is_online"))
}
img.onerror = function(){
document.body.removeChild(
document.getElementById("test_is_online"))
alert("断网了!")
}
img.src = "http://www.baidu.com/img/baidu_jgylogo3.gif"
img.style.display = "none"
document.body.appendChild(img)
}
window.onload = function(){
setInterval(isOnline, 10000)
}
每 10 秒钟检测一次,如果发现已经断网了,就会弹出对话框说:断网了
可以在javascript中ping一个ip地址:以下是自定义的实现函数:function Pinger_ping(ip, callback) { if(!this.inUse) {this.inUse = true this.callback = callbackthis.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)}}用法如下:传入ip和callback参数:比如192.0.8.10 和 mycallBacksetTimeout的返回值就可以判断了。static BufferedReader bufferedReaderpublic static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in)
System.out.print("请输入IP(180.97.33.107)或者域名(baidu.com):")
String address = input.next()
try {
Process process = Runtime.getRuntime()
.exec("ping " + address+" -t")//-t可以去掉
bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream()))
String connectionStr =null
while ((connectionStr = bufferedReader.readLine()) != null) {
System.out.println(connectionStr)
}
} catch (IOException e) {
System.out.println("链接失败")
e.printStackTrace()
} finally {
bufferedReader.close()
}
}
你试试这个代码