0

My Android/Kotlin application connects to a TCP server. Usually these three lines of code serve me well:

client1 = Socket(SERVER_IP_ADDRESS, SERVER_IP_PORT)
output1 = DataOutputStream (client1.getOutputStream())
input1 = DataInputStream (client1.getInputStream())

However, today the server is down and now I can see that the code hangs forever on the first line:

client1 = Socket(SERVER_IP_ADDRESS, SERVER_IP_PORT)

Can someone suggest any relatively easy way around this (I am an Android/Kotlin beginner)?

Thanks in advance

Garrett

***** UPDATE *****

Thanks to @useruser207421 and to this post, I am nearly there

My code now looks like this:

try {
  client1 = Socket()
  client1.connect(InetSocketAddress(SERVER_IP_ADDRESS, SERVER_IP_PORT), 3000)
  output1 = DataOutputStream (client1.getOutputStream())
  input1 = DataInputStream (client1.getInputStream())
} catch (ex : Exception) {
  // do something
} finally {
  // do something
}

However, the client1.connect() call does NOT timeout after the specified 3 seconds.

If the exception is a DNS error, it will fail immediately with

java.net.UnknownHostException

which is good.

However, the server was down earlier, and I am not sure what the exception was, but the exception was generated after 20 seconds, not 3.

So I will have to keep an eye on this - presumably I have got most, but not all, of the logic right.

garrettb
  • 139
  • 11

0 Answers0