第一次请求后结束NodeJS错误后的HTTP写操作

时间:2018-12-05 13:28:41

标签: node.js http tcp

我有一个TCP服务器,可以从IOT设备接收消息。收到消息后,我的TCP服务器通过 HTTP 将其发送到我的REST服务器。但是,在第一个请求成功发送后,当TCP服务器希望发送第二条消息时,出现结束后写入错误。

这是我在TCP服务器上的代码:

const net = require("net");
const server = net.createServer(onConnected);

const http = require("http");
const querystring = require('querystring');

//HTTP STUFF

const req = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding("utf8");
    res.on("data", (chunk) => {
        console.log(`BODY: ${chunk}`);
    })

    res.on("end", () => {
        console.log("no more data in res");
    })
});

req.on("error", (err) => {
    if (err.code === "ETIMEDOUT") {
        console.log("problem with request: connection timeout");
    } else if (err.code === "ECONNRESET") {
        console.log("problem with request: read timeout");
    } else {
        console.error(`problem with request: ${err.message}`);
    }
});

function send(postData) {
    console.log("start http");
    console.log("post data: " + postData);


    req.write(postData, function() {
        req.end();
    });


};

//TCP

server.listen(PORT, HOST, function() {
    console.log("Server listening on &j", server.address());
});

function onConnected(sock) {
    var remoteAddress = sock.remoteAddress + ":" * sock.remotePort;
    console.log("new client connected: %s", remoteAddress);

    sock.on("data", function(data) {
        console.log("%s says: %s", remoteAddress, data);
        let tcp_message = data.toString("utf8");
        let postData = querystring.stringify({
            "message": tcp_message
        });
        console.log("tcp message " + tcp_message)
        options.headers = {'Content-Length': Buffer.byteLength(postData) }
       send(postData);
       let mail_text = "Address: " + remoteAddress + " data: " + tcp_message;
    });

    sock.on("close", function(){
        console.log("connection from %s closed", remoteAddress);
    });

    server.on("error", function(err){
        console.log("connection %s error: %s", remoteAddress, err.message);
    });
}

0 个答案:

没有答案