当向服务器发送大量请求时,我遇到了java.net.SocketException
(权限被拒绝:连接)。我尝试了其他线程中提到的-Djava.net.preferIPv4Stack=true
选项。
只有在已经建立了很多连接之后才会出现此问题。以下代码可用于重现该问题:
public class Example {
public static void main(String[] args) {
if(args.length == 1) {
System.out.println(args[0]);
for(int i = 0; i < Integer.MAX_VALUE; i++) {
requestURL(args[0]);
}
}
}
public static void requestURL(String targetUrl) {
URL url = new URL(targetUrl);
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//handle response here
rd.close();
httpCon.disconnect();
}
}
代码将成功发送请求,直到发生异常。这已在服务器的日志文件中得到验证。
请仅针对您允许的服务器运行示例代码,因为它会在服务器上产生相当多的流量/负载。
所以现在的问题是:如何避免这种异常?或者任何变通方法?这里的实际问题是什么?
修改
添加了httpCon.disconnect()
。 (没有解决问题)
编辑#2(StackTrace)
java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.protocol.http.HttpURLConnection.connect(Unknown Source)
at Example.requestUrl(Example.java)
at Example.main(Example.java)
当问题发生时,不会向服务器发送进一步的请求(服务器上没有日志条目,也没有SYN数据包(使用tcpdump嗅探)。)
编辑#3
我忘了用-Djava.net.preferIPv4Stack=true
参数运行应用程序。
当使用前面提到的参数和httpCon.disconnect()
方法时,它还没有抛出异常。
答案 0 :(得分:1)
尝试使用httpCon.disconnect()以确保在完成读取响应后重新发布套接字。