在不关闭连接的情况下接收TCP消息

时间:2017-10-25 13:54:07

标签: jquery node.js ajax tcp

我的项目需要一些帮助。我需要在nodejs中接收TCP消息并通过Jquery Ajax将它们发送到Web界面。

请求在Web界面中触发,并通过ajax发送到node.js服务器。这个请求发送请求到TCP服务器(c ++)并将答案传递给webui。

我为测试purporses制作了一个功能,其中包括所有必要的任务。 function tcp_allinone(req,res){

    var vRequest = req.body.jsonmsg;
    console.log("< Info > tcp_allinone " + vRequest);

    if (tcpcl == undefined) {
        tcpcl = new net.Socket();
    } 

    tcpcl.connect(objTCPSocket.Port, objTCPSocket.Host, function () {
        tcpcl.write(vRequest);

    });

    tcpcl.on('data', function (data) {
        res.contentType('json');
        res.send({ data: data.toString() });
        tcpcl.end();
    });

    tcpcl.on('error', function (error) {
        res.contentType('json');
        res.send({ data: error.toString() });
        tcpcl.destroy();
    });


    tcpcl.on('close', function () {
        tcpcl.destroy();
        tcpcl = undefined;
    });

}

对于此项目,连接必须保持打开状态,并且不希望为每个请求重新打开连接。因此,我写入函数,一个用于启动套接字并打开连接,另一个用于写入和接收消息:

function tcp_starter(req,res){

    if (tcpcl == undefined) {
        tcpcl = new net.Socket();
    } 

    tcpcl.connect(objTCPSocket.Port, objTCPSocket.Host, function () {
        console.log("< Info > client_connect ");
        res.contentType('json');
        res.send({ data: "< Info > client_connect" });
    });

    tcpcl.on('error', function (error) {
        res.contentType('json');
        res.send({ data: error.toString() });           
        tcpcl.destroy();
    });

    tcpcl.on('close', function () {
        tcpcl.destroy();
        tcpcl = undefined;
    });

}

function tcp_writelisten(req,res){

        var vRequest = req.body.jsonmsg;
        console.log("< Info > tcp_writelisten " + vRequest);

        if (tcpcl !== undefined) {
            tcpcl.write(vRequest, function () {
                console.log("< Info > tcp_write: " + vRequest);
            });
        }

        tcpcl.on('data', function (data) {
            res.contentType('json');
            res.send({ data: data.toString() });
            console.log("< Info > tcp_listen: " + data.toString());
        });

}

tcp_starter在开始时调用,tcp_writerlisten每两秒从服务器获取新字符串。但是使用此构造,我收到以下错误消息: ttp.js:707     抛出新错误(&#39;在发送后无法设置标头。&#39;);           ^ 错误:发送后无法设置标头。     在ServerResponse.OutgoingMessage.setHeader(http.js:707:11)

我想问题是,每个函数调用tcp_writelisten我建立一个新的Eventlistener等等我得到i ++接收消息。

我如何在没有重新连接的情况下摧毁事件登记者(&#39;数据&#39;?我如何改善这种结构?

非常感谢您的帮助

0 个答案:

没有答案
相关问题