模拟Ping操作的一个Java类
本文为大家分享了模拟Ping操作的一个Java类,具体内容如下
importjava.io.IOException;
importjava.net.InetAddress;
importjava.net.UnknownHostException;
/**
*CreatedbyQiuJU
*on2014/9/21.
*/
publicclassSimplePingimplementsRunnable{
privatefinalObjectmEndLock=newObject();
privatebooleanIsEnd=false;
privateintarrivedCount=0;
privateintCount;
privateintTimeOut;
privateStringName;
privateintmEndCount;
privateStringmIp=null;
privatefloatmLossRate=1f;
privatefloatmDelay=0;
publicSimplePing(Stringname,intcount,inttimeOut){
Count=mEndCount=count;
TimeOut=timeOut;
Name=name;
for(inti=0;i<mEndCount;i++){
Threadthread=newThread(this);
thread.setDaemon(true);
thread.start();
}
if(!IsEnd){
try{
synchronized(mEndLock){
mEndLock.wait();
}
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
privatevoidsetEnd(booleanisArrived,longdelay,Stringip){
synchronized(mEndLock){
Count--;
if(isArrived){
arrivedCount++;
mDelay=(mDelay+delay)/2f;
if(ip!=null)
mIp=ip;
}
}
if(Count==0)
setEnd();
}
privatevoidsetEnd(){
mLossRate=(mEndCount-arrivedCount)/mEndCount;
IsEnd=true;
synchronized(mEndLock){
mEndLock.notifyAll();
}
}
@Override
publicvoidrun(){
longdelay=0;
booleanisArrived=false;
Stringip=null;
try{
longstartTime=System.currentTimeMillis();
InetAddressaddress=InetAddress.getByName(Name);
isArrived=address.isReachable(TimeOut);
delay=System.currentTimeMillis()-startTime;
ip=address.getHostAddress();
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
setEnd(isArrived,delay,ip);
}
}
publicStringgetIp(){
returnmIp;
}
publicfloatgetLossRate(){
returnmLossRate;
}
publicfloatgetDelay(){
returnmDelay;
}
publicbooleangetIsSucceed(){
returnarrivedCount>0;
}
}
在类中使用的是:
longstartTime=System.currentTimeMillis(); InetAddressaddress=InetAddress.getByName(Name); isArrived=address.isReachable(TimeOut); delay=System.currentTimeMillis()-startTime; ip=address.getHostAddress();
其中的:address.isReachable(TimeOut);方法,但是这个方法有一定局限性;当是Root模式下会发送ICMP进行Ping操作,这就比较真实了;但是如果是非Root模式下则是使用的Socket进行的模拟。
之所以说是中间类,也就是因为这个原因没有采用这个类。
以上就是本文的全部内容,希望对大家的学习有所帮助。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短