I have a function for sending data over Socket class in Java. When I send data I need to receive some data. The problem is how to set a timeout for waiting data on 2sec (if I don't receive data in 2sec I need to understand that happened a communication error and show 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 **********************************");
// 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;
开发者_StackOverflow 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;
}
See Socket and ServerSocket. Both classes have a setSoTimeout
method to specify the maximum time to wait when waiting for connections or waiting to receive data. When that time has elapsed, the socket throws a SocketTimeoutException
that you can handle with your error message or however you want.
You have to call setSoTimeout
before performing the actions you want to have a timeout.
Prior to
while ((numberReceived = socketInputStream.read(buffer)) != -1) {
You'll need to call
socket.setSoTimeout(2000);
And then add a catch(SocketTimeoutException)
section to the try/catch block you already have.
精彩评论