docs have a great example of how to connect to a server over a network.
var net = require('net');
var client = net.connect({port: 8124},
function() {
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
Just change the event handler data
to buffer incoming data until you get the information you need.
To do this, you will want to learn how to use it Buffer
.
Here is a concrete example of how to buffer data from a stream and parse messages limited to a specific character. I noticed in related PHP that the protocol you are trying to implement divides messages with the EOT character (0x04).
var net = require('net');
var max = 1024 * 1024
, allocate = 4096;
, buffer=new Buffer(allocate)
, nread=0
, nproc=0
, client = net.connect({host:'example.com', port: 8124});
client.on('data', function(chunk) {
if (nread + chunk.length > buffer.length) {
var need = Math.min(chunk.length, allocate);
if (nread + need > max) throw new Error('Buffer overflow');
var newbuf = new Buffer(buffer.length + need);
buffer.copy(newbuf);
buffer = newbuf;
}
chunk.copy(buffer, nread);
nread += chunk.length;
pump();
});
client.on('end', function() {
});
client.on('error', function(err) {
});
function find(byte) {
for (var i = nproc; i < nread; i++) {
if (buffer.readUInt8(i, true) == byte) {
return i;
}
}
}
function slice(bytes) {
buffer = buffer.slice(bytes);
nread -= bytes;
nproc = 0;
}
function pump() {
var pos;
while ((pos = find(0x04)) >= 0) {
if (pos == 0) {
slice(1);
continue;
}
process(buffer.slice(0,pos));
slice(pos+1);
}
}
function process(msg) {
if (msg.length > 0) {
}
}
, . , , , . , .