node.js http服务器并发问题

每当我尝试发送连续快速的HTTP POST,服务器有时崩溃(java.net.ConnectException:连接被拒绝:连接),有时会冻结(没有错误,但不能再使用它),有时工作….

如果我将HTTP Post慢慢发送到服务器,似乎没有任何问题。

我在node.js中有一个http服务器的简单代码 – 我的猜测是有时NodeJS服务器会收到一个请求,然后在发送响应之前接收到另一个请求,从而导致各种问题。 如何让我的服务器能够同时接受多个请求?

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); 

编辑这里是发送HTTP POST的Java程序

  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)); } } 

更新:如果我在nodejs服务器中parsingJSON,那么有时我会在连接被拒绝的地方出现错误。

所以,当我parsing请求数据,出于某种原因,nodejs无法接收发送的整个json文件(5KB)。 相反,它只接收它的一半,我的Java控制台说连接错误。 并且在nodejs正确分析大约3到5个请求之后发生此问题。 然后在下一个请求,一切都出错了。 如何判断java是否断开连接,只发送一半的JSON,或者只发送了一半的JSON导致nodejs崩溃,最终导致连接错误。

如果我注释掉所有的parsing,那么我再也不会得到错误了。 我甚至不明白为什么nodejs中的JSON.Parse会导致java连接错误….

你的问题在于:

  req.on('data', function(chunk) { //Do some stuff here file1=JSON.parse(chunk.toString()); console.log("Hello World") ; } 

由于主体可以被发送多个数据包,您可能会收到多个'data'事件,因此试图parsing不完整的JSON。 试试这个:

 var chunks = []; req.on('data', function(chunk) { chunks.push(chunk); } req.on('end', function () { // assemble all chunks var body = Buffer.concat(chunks).toString(), file1 = JSON.parse(body); res.writeHead(200, "OK", {'Content-Type': 'text/html'}); res.end(); }); 

在这种testing中,通过连接端口很容易达到最大吞吐量。

  1. http://www.slideshare.net/sh1mmer/a-million-connections-and-beyond-nodejs-at-scale
  2. https://groups.google.com/forum/#!topic/nodejs/cRRS7ZJkyzc

在运行node.js之前,简单的解决scheme是ulimit -n 100000 。 但是不要在生产中这样做,如果需要处理的话,最好考虑集群的真正的大连接。