简体   繁体   English

Java程序和网络连接超时

[英]Java program and network connection timeout

I have a java program that gather data from the web. 我有一个Java程序,可以从网上收集数据。 Unfortunately, my network has a problem and it goes off and on. 不幸的是,我的网络有问题,而且它一直在运行。
I need a trick to ask my program wait until the connection is on again and continue its job. 我需要一个技巧让我的程序等待直到再次打开连接并继续其工作。
I use the "URLConnection" library to connect. 我使用“ URLConnection”库进行连接。 I made a loop to reconnect when it a "ConnectException" is catched, but it doesn't work. 当捕获到“ ConnectException”时,我做了一个循环以重新连接,但它不起作用。
Any suggestions? 有什么建议么?

my network has a problem and it goes off and on. 我的网络有问题,它会断断续续。 I need a trick to ask my program wait until the connection is on again and continue its job 我需要一个技巧让我的程序等待直到再次打开连接并继续其工作

It depends on what your program's purpose is. 这取决于您的程序的目的。
How long are these intermittent failures? 这些间歇性故障要持续多长时间? If they are short enough you could use setConnectTimeout(0) to indicate an infinite timeout period while trying to connect but if your program has to report something back then it is not a good option for the end user. 如果它们足够短,则可以在尝试连接时使用setConnectTimeout(0)指示无限超时时间,但是如果您的程序必须报告某些内容,那么对于最终用户而言,这不是一个好选择。
You could set a relatively low timeout so that when you start to lose the network you will get a java.net.SocketTimeoutException . 您可以设置一个相对较低的超时,以便在您开始失去网络连接时会收到java.net.SocketTimeoutException
When you catch this, you could wait for a period and try again in a loop eg for 3 times and then perhaps report a failure. 当您发现此问题时,可以等待一段时间,然后循环尝试例如3次,然后报告故障。
It depends on what you are trying to do. 这取决于您要执行的操作。

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

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