SocketTimeoutException while readFully

1.2k views Asked by At

I have below code which throws SocketTimeoutException.

Socket socket = new Socket(localhost, 9978);
socket.setSoTimeout(10000);
OutputStream oStream= socket.getOutputStream();
byte[] data = new byte[] {'h', 'e', 'l', 'l', 'o'};
oStream.write(data);
oStream.flush();
DataInputStream iStream = new DataInputStream(socket.getInputStream());
final byte[] received = new byte[data.length];
data.readFully(received);

At readFully, I get SocketTimeoutException. So, certainly i have wrong code but I am not sure what.

Thanks for the help.

2

There are 2 answers

8
Scary Wombat On BEST ANSWER

How do you know that the server is sending you 5 bytes in return?

Maybe try using a normal read and see what happens.

Even a very slow server / network should be able to do 5 bytes in 10 seconds.

try this code

for (int x = 0; x < 5; x++) {
  byte[] received = new byte[1];
  data.readFully(received);
  System.out.println (new String (received));
}
0
user207421 On

You don't necessarily have 'wrong code'; maybe you have a slow network connection, or you're talking to a slow server. Try a longer timeout. Or maybe the server isn't sending you five bytes in reply.