Node.js net library: getting complete data from 'data' event

前端 未结 2 421
情书的邮戳
情书的邮戳 2021-01-12 05:19

I\'ve searched around, and either can\'t find the exact question I\'m trying to answer, or I need someone to explain it to me like I\'m 5.

Basically, I have a Node.j

2条回答
  •  日久生厌
    2021-01-12 06:12

    My problem was a logic problem. I was either looking for the chunk that began the message, or the chunk that ended the message, and ignoring everything in between. I guess expected the entirety of the reply to come in in one or two chunks.

    Here's the working code, pasted from above. There's probably a more Node-ish way of doing it (I should really emit an event for each chunk of information), but I'll mark this as the answer unless someone posts a better version by this time tomorrow.

    function connectToServer(tid, ip) {
            var conn = net.createConnection(23, ip);
    
            var completeData = '';
    
            conn.on('connect', function() {
                    conn.write (login_string);
            });
            conn.on('data', function(data) {
                    var read = data.toString();
    
                    if (read.match(/Login Successful/)) {
                            console.log ("Connected to " + ip);
    
                            conn.write(command_string);
                    }
                    else {
                            completeData += read;
                    }
    
                    if (completeData.match(/Command OK/)) {
                            if (completeData.match(/\r\nEND\r\n/)) {
                                    console.log("Response: " + completeData);
                            }
                    }
            });
            conn.on('end', function() {
                    console.log("Connection closed to " + ip );
            });
            conn.on('error', function(err) {
                    console.log("Connection error: " + err + " for ip " + ip);
            });
    }
    

提交回复
热议问题