0

我编写了一些代码来定期将数据发布到 NodeJs 程序,该程序侦听 POST 并打印数据。然而,有时头球可以通过,有时头球和身体都可以通过。这是发布数据的 Java 代码:

JSONObject dataObject = new JSONObject();
dataObject.put("test", "true");
URLConnection urlConn = thisSubUrl.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput(true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
String dataStr = dataObject.toString();
wr.write(dataStr, 0, dataStr.length());
wr.flush();
wr.close();

BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
in.close();

服务器代码如下所示:

var server= http.createServer(function(req,res){
req.setEncoding('utf8');
console.log(req.headers);
req.on('data', function(chunk) {
          console.log("Receive_Event::" + chunk);
         });
req.on('end', function() {
    console.log('on end');
});

console.log("Bytes received: " + req.socket.bytesRead);
if(req.method=='POST'){
    handlePost(req,res);
} else{
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end();
}
}).listen(1338, "127.0.0.1");

标题总是被打印出来。接收到的字节数在长度上有所不同,在标头中的字节数和标头中的字节数 + 正文长度之间。

为什么会这样?

4

1 回答 1

1

可能发生的情况是,在您收到所有“数据”块之前,您将发出res.end()(不知道实际做了什么)。handlePost您应该在“结束”事件中调用所有额外的逻辑

var server= http.createServer(function(req,res){
    req.setEncoding('utf8');

    console.log(req.headers);

    req.on('data', function(chunk) {
        console.log("Receive_Event::" + chunk);
    });

    req.on('end', function() {
        console.log('on end');
        console.log("Bytes received: " + req.socket.bytesRead);
        if(req.method=='POST'){
            handlePost(req,res);
        } else{
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end();
        }
    });


}).listen(1338, "127.0.0.1");
于 2012-05-08T08:53:27.697 回答