我有通过套接字发送消息和接收答案的方法。如何放置计时器,如果没有答案,例如1秒放信息超时?
public boolean SendForceMessage(final ForceMessageTCP message) {
boolean result = true;
System.out.println("******************SendForceMessage**********************************");
new Thread() {
public void run() {
try {
System.out.println("IPADDRESS="+ipAddress);
System.out.println("PORT="+port);
System.out.println("Is reachable="+Ping());
for(int i=0;i<message.ToBytes().length;i++)
System.out.println("FRAGMENT["+i+"]="+message.ToBytes()[i]);
socket = new Socket(ipAddress, port);
OutputStream socketOutputStream = (OutputStream) socket
.getOutputStream();
socketOutputStream.write(message.ToBytes());
InputStream socketInputStream=(InputStream)socket.getInputStream();
byte[] buffer=new byte[256];
int numberReceived=socketInputStream.read(buffer);
if(numberReceived!=-1)
new FDResponseMessage(buffer);
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
return result;
}
答案 0 :(得分:3)
http://www.javacoffeebreak.com/articles/network_timeouts/
快乐阅读
修改的
忘记套接字选项,请查看:http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#setSoTimeout(int)
基本上您设置了 SO ,因此您对 read()的调用只会阻止您指定的时间