无法使用 net.createConnection() 获取单个数据回调;

Unable to get individual data callbacks with net.createConnection();

我是 Node.js 概念的新手。我正在研究使用 Unix 套接字作为 C 和 Node.js 之间的通信方式。

在 C: 我正在发送 100 字节长消息的 1000 次迭代。

在Node.js: 我收到 4 个大小的数据回调:

我知道我能够收到完整的数据。但是,我如何在 1000 个大小为 100 字节的回调中获取此数据(与我发送它的方式相同)。

代码参考

C 中的服务器(部分):

char buf[100];
int loop_count = 0;
memset(buf,0xA5,sizeof(buf));
while(loop_count < 1000) {
    rc = sizeof(buf);
    if (write(cl, buf, rc) != rc) {
        if (rc > 0) fprintf(stderr,"partial write");
        else {
            perror("write error");
            exit(-1);
        }
    }
    ++loop_count;
}

Node.js 中的客户端:

var net = require('net');
var client = net.createConnection("temp");
#temp is the socket file name

client.on("connect", function() {
    console.log("Connection established");
});

client.on("data", function(data) {
   console.log("Found data "+data);
});    

套接字缓冲区数据,因此当您将 100 字节的块写入套接字时,reader 不一定会以整齐的 100 字节块读取数据。

您可以使用 block-stream 之类的模块为您将数据拆分为 100 字节的块:

const BlockStream = require('block-stream');
const net         = require('net');
const client      = net.createConnection('temp');
const bs          = new BlockStream(100);

let count = 0;

client.pipe(block).on('data', function(data) {
  count++;
  console.log('Found data: ', data);
}).on('end', function() {
   console.log('Read %s blocks', count);
});