我有一个简单的多线程服务器,线程的代码如下所示:
public void run(){
while(Ecoute()){
str=LireTrame(this.socClient);//read text byte by byte
//some code here
Dormir(500);//Sleep for 500ms
}
}
我想创建 3 分钟的超时,如果客户端套接字在 3 分钟内没有发送消息,则必须关闭线程...
所以我尝试这样做:
public void run(){
try {
socClient.setSoTimeout(180000);//timeout for 3 min...
} catch (SocketException ex) {
Logger.getLogger(tache.class.getName()).log(Level.SEVERE, null, ex);
}
while(Ecoute()){
try{
str=LireTrame(this.socClient);//read text byte by byte
}
catch(java.net.SocketTimeoutException ex){
log.append("timeout exception has benn catched \n") ;
break;//break the while
}
//some code here
Dormir(500);//Sleep for 500ms
}
}
问题是 netbeans 显示错误消息:
java.net.SocketTimeoutException never thrown in body of corresponding try statement
我用 SocketException 尝试了这个,但结果相同..
为什么我抓不到他们?
更新:根据 thinksteep 和 mprabhat 的回复,我在 LireTrame(..) 中添加了th throw,但我仍然无法捕捉到异常:
public String LireTrame(Socket socClient) throws java.net.SocketTimeoutException{
int c = 0;
String Nmea="";
boolean finL=true;
do{
try {
c=socClient.getInputStream().read();
} catch (IOException ex) {
Logger.getLogger(tache.class.getName()).log(Level.SEVERE, null, ex);
}
char ch=(char)c;
Nmea=Nmea+ch;
if(ch==';')
finL=false;
}while(finL);
return Nmea;
}
mai 11, 2012 8:04:02 PM Daemon.tache LireTrame
Grave: null
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:150)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at java.net.SocketInputStream.read(SocketInputStream.java:203)
at Daemon.tache.LireTrame(tache.java:232)
at Daemon.tache.run(tache.java:87)
at java.lang.Thread.run(Thread.java:722)
有什么想法可以做到这一点吗?