I am trying to send some HTTP requests continuously to a server using Java.
Socket socket = new Socket("ip.address", port);
socket.setKeepAlive(true); //it does not help
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
for(int i=1;i<50;i++){
String data = "some data " + i;
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + data.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
wr.write(data);
wr.flush();
}
wr.close();
socket.close();
The server receives only the first request, then the program terminates by throwing the exception
java.net.SocketException: Software caused connection abort: socket write error
So, I tried this way, creating socket & closing inside the loop every time:
for(int i=1;i<50;i++){
Socket socket = new Socket("ip.address", port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
String data = "some data " + i;
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + data.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
wr.write(data);
wr.flush();
wr.close();
socket.close();
}
It works fine as I had expected. The server receives all the requests.
Questions:
Is the second approach correct way to do? If I open & close every time, will it not affect the performance in general? Or How can I improve the first approach?
Is there any other better approach to send HTTP requests? (It does not have to be using sockets). Performance is VERY important for us.
Connection: keep-aliveto the first example and see if it works any better for you.