I have a function to send data on the Socket class in Java. When I send data, I need to get some data. The problem is how to set a timeout for waiting for data for 2 seconds (if I do not receive data in 2 seconds, I need to understand what a communication error message is and showing a message). This is my code, any help?
public boolean SendMonitorMessage(
final MonitorRequestRepeatMessageTCP message) {
boolean result = true;
System.out
.println("****************** SEND MONITOR REQUEST REPEAT MESSAGE TCP **********************************");
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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
Damir source
share