亲宝软件园·资讯

展开

模拟Ping操作的Java类 模拟Ping操作的一个Java类

人气:0
想了解模拟Ping操作的一个Java类的相关内容吗,在本文为您仔细讲解模拟Ping操作的Java类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java类,Ping操作,下面大家一起来学习吧。

本文为大家分享了模拟Ping操作的一个Java类,具体内容如下

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
 
/**
 * Created by QiuJU
 * on 2014/9/21.
 */
public class SimplePing implements Runnable {
 private final Object mEndLock = new Object();
 private boolean IsEnd = false;
 
 private int arrivedCount = 0;
 
 private int Count;
 private int TimeOut;
 private String Name;
 
 private int mEndCount;
 private String mIp = null;
 private float mLossRate = 1f;
 private float mDelay = 0;
 
 
 public SimplePing(String name, int count, int timeOut) {
  Count = mEndCount = count;
  TimeOut = timeOut;
  Name = name;
  for (int i = 0; i < mEndCount; i++) {
   Thread thread = new Thread(this);
   thread.setDaemon(true);
   thread.start();
  }
  if (!IsEnd) {
   try {
    synchronized (mEndLock) {
     mEndLock.wait();
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 private void setEnd(boolean isArrived, long delay, String ip) {
  synchronized (mEndLock) {
   Count--;
   if (isArrived) {
    arrivedCount++;
    mDelay = (mDelay + delay) / 2f;
    if (ip != null)
     mIp = ip;
   }
  }
  if (Count == 0)
   setEnd();
 }
 
 private void setEnd() {
  mLossRate = (mEndCount - arrivedCount) / mEndCount;
 
  IsEnd = true;
  synchronized (mEndLock) {
   mEndLock.notifyAll();
  }
 }
 
 @Override
 public void run() {
  long delay = 0;
  boolean isArrived = false;
  String ip = null;
  try {
   long startTime = System.currentTimeMillis();
   InetAddress address = InetAddress.getByName(Name);
   isArrived = address.isReachable(TimeOut);
   delay = System.currentTimeMillis() - startTime;
   ip = address.getHostAddress();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   setEnd(isArrived, delay, ip);
  }
 }
 
 public String getIp() {
  return mIp;
 }
 
 public float getLossRate() {
  return mLossRate;
 }
 
 public float getDelay() {
  return mDelay;
 }
 
 public boolean getIsSucceed() {
  return arrivedCount > 0;
 }
}

在类中使用的是:

long startTime = System.currentTimeMillis();
   InetAddress address = InetAddress.getByName(Name);
   isArrived = address.isReachable(TimeOut);
   delay = System.currentTimeMillis() - startTime;
   ip = address.getHostAddress();

其中的:address.isReachable(TimeOut);方法,但是这个方法有一定局限性;当是Root模式下会发送ICMP进行Ping操作,这就比较真实了;但是如果是非Root模式下则是使用的Socket进行的模拟。
之所以说是中间类,也就是因为这个原因没有采用这个类。

以上就是本文的全部内容,希望对大家的学习有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论