简体   繁体   English

超时InetSocketAddress

[英]time out for InetSocketAddress

I have the following code: 我有以下代码:

socket.connect(new InetSocketAddress(serverHost, serverPort), CONNECT_TIMEOUT);

The problem is that when the DNS is not accessible the InetSocketAddress takes 45sec to timeout and return an exception ("Host in not accessible..."). 问题是当DNS无法访问时,InetSocketAddress需要45秒才能超时并返回异常(“主机不可访问...”)。 I need the entire command (so the creation of InetSocketAddress and the connect to timeout earlier. I did not find a way to make the new InetSocketAddress(serverHost, serverPort) timing out earlier. 我需要整个命令(因此创建了InetSocketAddress并提前连接到超时。我没有找到一种方法使new InetSocketAddress(serverHost, serverPort)提前超时。

Is it possible? 可能吗?

PS I'm on Android but the problem is the same on other platform PS我在Android上,但问题在其他平台上是一样的

There is no easy way. 没有简单的方法。 You need to run this code 您需要运行此代码

socket.connect(new InetSocketAddress(serverHost, serverPort), CONNECT_TIMEOUT);

in a separate thread (i/o thread) and communicate with it from UI main thread. 在一个单独的线程(i / o线程)中,并从UI主线程与它进行通信。 Once you are over your time limit - send it a terminate signal and proceeding in UI thread immediately, don't wait till it does terminate. 一旦超过你的时间限制 - 发送一个终止信号并立即进入UI线程,不要等到它终止。 Depending on the state, the i/o thread either dies immediately or eventually. 根据状态,I / O线程立即或最终死亡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM