Search code examples
javasocketexceptionsocket-timeout-exception

SocketTimeoutException while readFully


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.


Solution

  • 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));
    }