我正在尝试从套接字读取项目,我注意到如果套接字流上没有任何内容,它将保留在读取并备份我的应用程序。我想知道是否有办法设置读取超时或在套接字中没有任何时间后终止连接。
答案 0 :(得分:22)
如果您编写Java,学习导航the API documentation会很有帮助。如果是套接字读取,您可以set the timeout option.
答案 1 :(得分:0)
如果此套接字是通过URLConnection
创建的来执行Web请求,则可以在读取流之前直接在URLConnection
上设置读取和连接超时:
InputStream createInputStreamForUriString(String uriString) throws IOException, URISyntaxException {
URLConnection in = new URL(uriString).openConnection();
in.setConnectTimeout(5000);
in.setReadTimeout(5000);
in.setAllowUserInteraction(false);
in.setDoInput(true);
in.setDoOutput(false);
return in.getInputStream();
}
答案 2 :(得分:-6)
是的,应该覆盖Read()接受超时值。通过'覆盖'我不建议任何人写一个,我指出他正在使用的套接字方法的一个覆盖采用超时值。