java 为 readLine() 设置超时限制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7937668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:05:37  来源:igfitidea点击:

Setting a time-out limit to readLine()?

javasocketspop3

提问by Carven

I have the following code that reads response from a POP server through Sockets in Java. But the problem is sometimes, when I use the readLine() function to read from the server and if the server does not reply with any response, my application will hang there, waiting for a response from the server.

我有以下代码通过 Java 中的套接字读取来自 POP 服务器的响应。但问题是有时,当我使用 readLine() 函数从服务器读取时,如果服务器没有回复任何响应,我的应用程序将挂在那里,等待服务器的响应。

socket.connect(new InetSocketAddress("pop.server.com", 110), 3000);
input = socket.getInputStream();
BufferedReader incoming = new BufferedReader(new InputStreamReader(input));
incoming.readLine();   //This line will cause my application to hang if the server does not respond with a reply

Is there a way to set a timeout or some other ways that when the server does not reply after a certain amount of time, the application should stop waiting for a response and continue its other execution?

有没有办法设置超时或其他一些方法,当服务器在一定时间后没有回复时,应用程序应该停止等待响应并继续其其他执行?

采纳答案by Peter Lawrey

I suggest you try Socket.setSoTime(timeout)

我建议你试试Socket.setSoTime(timeout)