我有通过Java在Socket类上发送数据的功能。当我发送数据时,我需要接收一些数据。问题是如何在2秒内设置等待数据的超时(如果我在2秒内没有收到数据,我需要理解通信错误和显示消息)。 有我的代码,有什么帮助吗?
public boolean SendMonitorMessage(
final MonitorRequestRepeatMessageTCP message) {
boolean result = true;
System.out
.println("****************** SEND MONITOR REQUEST REPEAT MESSAGE TCP **********************************");
// new Thread() {
// public void run() {
int prevService=message.GetService();
synchronized (socket) {
try {
System.out.println("IPADDRESS=" + ipAddress);
System.out.println("PORT=" + port);
System.out.println("Is reachable=" + Ping());
message.PrintMessage(message.toBytes());
OutputStream socketOutputStream = (OutputStream) socket
.getOutputStream();
socketOutputStream.write(message.toBytes());
InputStream socketInputStream = (InputStream) socket
.getInputStream();
byte[] buffer = new byte[256];
List<byte[]> received = new LinkedList<byte[]>();
int numberReceived;
byte[] tempBuffer;
while ((numberReceived = socketInputStream.read(buffer)) != -1) {
tempBuffer = new byte[numberReceived];
ByteBuffer baferce = ByteBuffer.wrap(tempBuffer);
baferce.put(buffer, 0, numberReceived);
received.add(tempBuffer);
}
if (received.size()>0){
new MonitorResponseMessageTCP(received, message.GetMonitorVariablesArrayList(), prevService);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
答案 0 :(得分:6)
请参阅Socket和ServerSocket。这两个类都有setSoTimeout
方法来指定等待连接或等待接收数据时等待的最长时间。当该时间结束时,套接字会抛出一个SocketTimeoutException
,您可以使用错误消息处理该问题,或者您想要处理。
在执行您想要暂停的操作之前,您必须先致电setSoTimeout
。
之前
while ((numberReceived = socketInputStream.read(buffer)) != -1) {
您需要致电
socket.setSoTimeout(2000);
然后将catch(SocketTimeoutException)
部分添加到您已有的try / catch块中。