在接收消息中添加超时 - 套接字
问题描述:
我有通过套接字发送消息并接收答案的方法。如何把计时器,如果没有答案,例如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;
}
答
http://www.javacoffeebreak.com/articles/network_timeouts/
快乐阅读
编辑
忘了socket选项,请检查了这一点:http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#setSoTimeout(int)
基本上你设置一个SO,为此你的来电到read()将只会阻塞您指定的时间量