用NIO socket读取网络数据,找了好久没找到,NIO下设置读超时的API,只好自己写了一个。
思路是设置守护进程,启动后等待 一定的时间,如果在等待一定的时间后还没被唤醒,则抛出超时异常。
//设置超时守护进程
TimeOutThread t = new TimeOutThread(5000,new TimeoutException("reading timeOut"));
t.start();
count=client.read(protocalNum);
count=client.read(functionNum);
count=client.read(messageLen);
messageLen.rewind();
int length = messageLen.asIntBuffer().get(0);
receivebuffer = ByteBuffer.allocate(length-12);
receivebuffer.clear();
count=client.read(receivebuffer);
t.cancel();
notifyAll();
TimeOutThread.java
private long timeOut ;
private boolean isCanceled = false;
private TimeoutException exception;
public TimeOutThread(long timeOut,TimeoutException exception){
super();
this.timeOut = timeOut;
this.exception = exception;
this.setDaemon(true);
}
public synchronized void cancel(){
this.isCanceled = true;
}
public synchronized void run(){
try{
wait(timeOut);
if(!isCanceled){
throw exception;
}
}
catch(InterruptedException e){
e.printStackTrace();
}
}
TimeOutException.java 就不写了。