Nodejs - 服务器和客户端之间的数据传输

时间:2016-05-20 06:14:22

标签: node.js tcp

我已经给出了一个任务,只要找到要发送的新记录,就可以将json字符串从客户端发送到服务器,并将服务器发送到客户端。所以我决定在服务器和客户端之间建立TCP连接(建议我,如果在nodejs中还有其他更好的方法)来传输数据。 问题是,我应该使用分隔符将json字符串彼此分开。如果json字符串包含对象内的分隔符字符串,我担心怎么办?所以我想要一种更完美的方式来分离两个json字符串。以下是我的代码。请帮帮我。

客户端

var net = require('net')
    , client = new net.Socket();

var chunk = ''
    , dlim_index = -1
    , delimit = '~~';


client.connect(config.Port, config.IpAddress, function () {
    console.log('Server Connected');
    client.write('CLIENTID:' + process.argv[2]);
    client.write(delimit);
});

client.on('data', function (data) {

    var recvData = data.toString().trim();
    chunk += recvData;
    dlim_index = chunk.indexOf(recvData);
    console.log(data);
    while (dlim_index > -1) {
        var useData = chunk.substring(0, dlim_index);
        if (useData == 'SUCCESS') {
            controller.listenOutQueue(function (dataToSend) {
                var object = JSON.parse(dataToSend);
                client.write(dataToSend);
                client.write(delimit);
            });
        }
        else {
            var record = JSON.parse(useData);
            controller.insertIntoQueue(record, function (status) {
            });
        }
        chunk = chunk.substring(dlim_index + 2);
        dlim_index = chunk.indexOf(delimit);
    }
});

client.on('close', function () {
    console.log('Connection closed');
});

client.setTimeout(50000, function () {
    //client.destroy();
});

服务器

var net = require('net')
    , server = net.createServer()
    , delimit = '~~'
    , clients = [];

controller.listenOutQueue(function (dataToSend) {
    client.write(dataToSend);
    client.write(delimit);
});

server.on('connection', function (socket) {


    var chunk = '';
    var dlim_index = -1;

    socket.on('data', function (data) {

        var recvData = data.toString().trim();
        chunk += recvData;
        dlim_index = chunk.indexOf(delimit);

        while (dlim_index > -1) {
            var useData = chunk.substring(0, dlim_index);
            if (useData.substring(0, 9) == 'CLIENTID:') {
                socket.clientid = useData.replace('CLIENTID:', '');
                console.log('Client Id: ' + socket.clientid);
                clients.push(socket);
                var successMessage = "SUCCESS";
                socket.write(successMessage);
                socket.write(delimit);
            }
            else {

                controller.insertIntoQueue(JSON.parse(useData), function (status) {
                });
            }
            chunk = chunk.substring(dlim_index + 2);
            dlim_index = chunk.indexOf(delimit);
        }
    });

    socket.on('end', function () {
        console.log('Connection Closed (' + socket.clientid + ')');
    });

    socket.on('error', function (err) {
        console.log('SOCKET ERROR:', err);
    });

});

server.listen(config.Port, config.IpAddress);

0 个答案:

没有答案