NodeJS TCP Server,onData小块 [英] NodeJS TCP Server, onData small chunks

查看:706
本文介绍了NodeJS TCP Server,onData小块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个简单的NodeJS TCP服务器,Java客户端发送图像:

I made a simple NodeJS TCP server which a Java Client sends an image:

encodedImage = <a base64 encoded image>
out.write("IMG;" + encodedImage);
out.flush();

我的NodeJS服务器如下:

My NodeJS server is as follows:

net.createServer(function(TCPSocket){
        TCPSocket.on("data", function(data){
            console.log("TCP Recieved: " + data.length);    
        });
}).listen(5000);

但是,即使我发送所有数据并立即冲洗它,输出如下:

However, even if I send all data and flush it immediately, the output is as follows:

TCP Recieved: 13
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1472
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344

我想让它在一个简单的块中收到它,但我认为它由于NodeJS的事件处理机制而发生了什么,对于作为单个块发送的数据实现单块数据的最佳方法是什么?据我所知,TCP窗口可能比1344字节的数据大得多。我想把头文件值用作HTTP,所以我知道ad构造我想要的对象的长度。

I want it to recieve it in a simple chunk, but I assume it is happenng due to NodeJS's event handling mechanism, what is the best way to achieve single chunk of data for data sent as a single chunk? As far as I know, a TCP window can be much larger than 1344 bytes of data. I thought of using header values as HTTP so I know the length ad construct the object I want.

推荐答案

你是对的,在Node中,数据将进入分块状态。您需要保留一个缓冲区,连接所有进入的块,然后当套接字关闭时,将数据写入文件系统。这是一个能够接收图像的示例:

You're correct, in Node the data will come in chunked. You'll need to keep a buffer, concatenating all the blocks that come in and then when the socket is closed, write your data out to the file system. Here is an example that was able to receive an image:

net = require('net');
fs = require('fs');

net.createServer(function(socket){
  var buffer = new Buffer(0, 'binary');

  socket.on("data", function(data){
    buffer = Buffer.concat([buffer, new Buffer(data,'binary')]);
  });

  socket.on("end", function(data) {
    fs.writeFile("image.jpg", buffer, function(err) {
      if(err) {
        console.log(err);
      } else {
        console.log("Socket[" + socket.name + "] closed, wrote data out to sinfo.data");
      }
    }); 

  });

}).listen(5000);

console.log('ready');

我使用 netcat

$ netcat localhost 5000 < input.jpg

这篇关于NodeJS TCP Server,onData小块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆