1

I have a Java socket connection established with a server A. Server A randomly restarts during the day and my Java socket connection infinitely waits because it thinks that is receiving data. I have set the soTimeout but it is only kicking in while read is still going on. How do I set force a timeout on the socket connection? I want to break the socket connection after a set period of time.

Socket mySocket = new Socket(host, port) ;
mySocket.setKeepAlive(true);
mySocket.setSoTimeout(timeout);
2
  • 1
    Try using a Timer thread then close the socket when done Commented Nov 20, 2020 at 21:15
  • You can't know about the other side of the connection unless you try to read/write from the server socket. I would try to check read something, manage the exception and close the connection. Commented Nov 20, 2020 at 21:46

1 Answer 1

1

You don't need to break the connection periodically. You may just use TCP Keepalive mechanism to send small "ping" requests in defined intervals. Whenever one of parties does not respond, TCP connection is closed. More info here: https://en.wikipedia.org/wiki/Keepalive

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.