Nodejs net.createServer large amount of data coming in

I have nodejs listening on tcp port and getting content from Flash XMLSocket. If I try to push a lot of data in one message from the flash ( XMLSocket.send(long_message) ), I always get the stream.on("data", function(d) { event when I want this to happen when the whole message is transmitted Flash XMLSocket transfers data as a UTF8 encoded string with a zero byte. How can I control my message sequence?

UPDATE

I found a similar question here . But there is no clear answer. I know that the end of my message should be a null byte, but could you give me an example of how to store an incomplete message and avoid matching with the next / parallel message.

UPDATE2

After maerics answer, I did something like

  var server = net.createServer(function(stream) { var dataBlock = ""; stream.on("data", function(d) { processChunk(d); }); function processChunk(data) { var chunks = data.split("\0"); while (chunks.length > 1) { if (dataBlock.length > 0) { dataBlock += chunks.shift(); processIncompingMessage(dataBlock); dataBlock = ""; } else { processIncompingMessage(chunks.shift()); } } dataBlock += chunks.shift(); } } 
+4
source share
1 answer

Here 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 = ''; } }); }); 

Please note that it is possible that several messages isolated from zero can be encoded in one data block, so you should expand this example to divide the data into zero characters and process each separately. In addition, you can handle the final, potentially incomplete message in the 'end' connection event.

+3
source

Source: https://habr.com/ru/post/1393853/


All Articles