nodejs net.createServer large amount of data coming in

I have nodejs listening on tcp port and gets content from Flash XMLSocket. If I try to push a lot of data in one message from flash ( XMLSocket.send(long_message)
) I always end up with event stream.on("data", function(d) {
fired while I want it to happen when entire message is transferred. Flash’s XMLSocket transfers data as UTF8 encoded string terminated with null byte. How can I control my message consistency?

UPDATE

I’ve found similar question here
. But there is no clear answer. I know the end of my message should be null byte, but could you please give me an example on how to store incomplete message and avoid overlapping with next/concurrent message

UPDATE2

After maerics’s answer I’ve done something like

var server = net.createServer(function(stream) {
    var dataBlock = "";
    stream.on("data", function(d) {
            processChunk(d);
    });

    function processChunk(data) {
            var chunks = data.split("");
            while (chunks.length > 1) {
                    if (dataBlock.length > 0) {
                            dataBlock += chunks.shift();
                            processIncompingMessage(dataBlock);
                            dataBlock = "";
                    }
                    else {
                            processIncompingMessage(chunks.shift());
                    }
            }
            dataBlock += chunks.shift();
    }
    }

Problem courtesy of: Dmytro Leonenko

Solution

Here’s what I would do (tested):

var net = require('net');

var server = net.createServer(function (conn) {
  var msg = ''; // Current message, per connection.

  conn.setEncoding('utf8');

  conn.on('message', function (m) {
    console.log('MESSAGE: ' + m);
  });

  conn.on('data', function (data) {
    msg += data.toString('utf8');

    if (msg.charCodeAt(msg.length - 1) == 0) {
      conn.emit('message', msg.substring(0, msg.length - 1));
      msg = '';
    }
  });
});

Note that it is possible that multiple null separated messages could be encoded in a single data chunk, so you should expand this example to separate the data by null characters and process each one separately. Also, you might want to process the final, potentially incomplete message on the connection 'end'
event.

Solution courtesy of: maerics

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » nodejs net.createServer large amount of data coming in

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录