1

I have a Java application with three threads that open, each, a socket and connect to a server on different ports. I set so_timeout on each of these sockets after the connection to the server is established. After that the threads block waiting on read(). Only one of the threads times out after 20 seconds (which is the timeout I set). The other two ignore the timeout. Is it possible that the TCP layer handles only one timeout at a time? Is there any other explanation?

arsenalfan
  • 81
  • 2
  • 10
  • Please post your code, you may have a sneaky logic error that cannot be caught by your question. – Jonathan Aug 20 '09 at 13:25
  • Make a call to sock.getSoTimeout() just to make sure it returns 20000. Post some code too. What OS are you running on? – Nick Aug 20 '09 at 20:36
  • Here's the code to to establish connection: while (!connected) { try { client = new Socket(); InetSocketAddress sa = new InetSocketAddress(serverIP, port); client.connect(sa); client.setKeepAlive(true); } catch (UnknownHostException e) { e.printStackTrace(); return null; } catch (IOException e) { ... } if (client.isConnected()) { // Set timeout for blocking read operations. try { client.setSoTimeout(timeout*1000); } catch (SocketException e) {} connected = true; } } – arsenalfan Aug 25 '09 at 05:07
  • And the code that waits on read: try { // Get the input channel in = new BufferedInputStream(clientSocket.getInputStream()); } catch (IOException e) {} while (isActive) { try { bytesRead = in.read(message, 0, BUF_SIZE); } catch (SocketTimeoutException STE) { ... } catch(IOException IOE){ ... } if (bytesRead > 0)processInput(message, 0, bytesRead); } – arsenalfan Aug 25 '09 at 05:10
  • 1
    I did verify that so_timeout is set. – arsenalfan Aug 25 '09 at 05:11
  • I have never had this problem since Windows 95 or even before with the separelty distributed TCP/IP stack. You are doing something wrong. Code please. – user207421 Feb 01 '19 at 11:17

2 Answers2

3

The documentation says:

The option must be enabled prior to entering the blocking operation to have effect.

maybe you should set it before the connection to the server is established, at least before calling read() on the socket.
But hard to say without the code...

user85421
  • 28,957
  • 10
  • 64
  • 87
3

I've had several problems in the past dealing with SO_TIMEOUT in windows. I believe setting this is "supposed" to set the underlying socket implementation that could be OS dependent and conflicting with registry settings and such.

My advice is to not use SO_TIMEOUT to force a thrown exception on a timeout. Use either non-blocking I/O or check that you have bytes available() before you read().

Nick
  • 1,340
  • 1
  • 15
  • 23