Whenever I try to to send rapid HTTP Post in succession, the server sometimes crashes (java.net.ConnectException: Connection refused: connect), sometimes freezes (no error, but cannot use it anymore), and sometimes works....
If I send HTTP Post to the server slowly, there seems to be no problems at all.
I have the simple code for an http server in node.js - My guess is that sometimes the NodeJS server will receive a request, then receive another request before it sends out the respond, thus causing all sorts of problem. How do I make my server able to accept multiple requests all at once?
var server = http.createServer(function (req, res) {
if (req.method != 'POST') {
res.end();
}
else {
req.on('data', function(chunk) {
//Do some stuff here
file1=JSON.parse(chunk.toString());
console.log("Hello World") ;
}
req.on('end', function() {
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.end();
});
}
} server.listen(9000);
EDIT Here is the java program sending the HTTP POSTS
public static String httpUrlRequest(String requestURL, String json) {
URL url;
String response = "";
HttpURLConnection connection = null;
InputStream is = null;
try {
url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.getOutputStream().write(json.getBytes());
connection.getOutputStream().flush();
connection.getOutputStream().close();
int code = connection.getResponseCode();
System.out.println("code" + code);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return response;
}
public static void main(String[] args) {
Date date = new Date();
Gson gson = new Gson();
Map<String, Object> tempMap = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
for(int i = 0; i < 10; i++){
date = new Date();
tempMap.put("GetOn", getDateString(date));
httpUrlRequest("http://111.111.11.111:9000" ,gson.toJson(tempMap));
}
}
UPDATE : If I parse the JSON in the nodejs server, then sometimes I get the error where the connection is refused.
So when I parse the request data, for some reason, nodejs fails to receive the entire json file that was sent (5KB). Instead, it only receives half of it, and my Java console says connect error. And this problem occurs AFTER nodejs correctly parses about 3 to 5 requests. Then on the next request, everything goes wrong. How can I tell if the java breaks connection causing only half of the JSON to be sent, or if only half of the JSON is sent causing nodejs to crash, ultimately resulting in connect error.
If I comment out all the parsing, then I never get the errors anymore. I don't even understand why JSON.Parse in nodejs would induce a java connect error....
java.net.ConnectException: Connection refused: connect. The file being parsed is about 5 KB