How to separate TCP socket messages in node.js

I cut my teeth with TCP sockets and am confused by the way the messages arrive in my application. It looks like they are broken. Does anyone know how I can join them together? All messages are separated by a line break (\ r \ n)

var stream = net.createConnection(port,host); stream.setEncoding("utf8"); stream.on('data', function(chunk){ console.log('data: ' + sys.inspect(chunk)); }); 

An example of what the console unloads is as follows:

 data: '0' data: '5293800791D04\r' data: '\n' data: '053138007928F1\r\n' data: '05313800012869\r\n' data: '052E3800790E0E\r\n' data: '052E3800010E86\r\n' data: '05223' data: '8007933F5\r\n' data: '05213800791019\r\n' data: '05213800795C795B79265A\r\n' data: '05213800011091\r\n' 

I need to break the material on the line so that I don't have incomplete messages. Is there a way to tell node to do this for me? If not, does anyone have any examples of how this can be done?

+4
source share
2 answers

I found a module called a β€œcarrier” that does exactly what I need. After installing the module, it was as easy as adding this:

 carrier.carry(stream, function(line) { console.log("line: "+line) }) 

I found the answers here:

http://nodetuts.com/tutorials/5-a-basic-tcp-chat-server.html

https://github.com/pgte/carrier

+5
source

Since TCP is a stream protocol (not a block protocol), it does not support any boundaries between what you can consider as separate messages. This is the recipient's answer if you need to collect high-level messages from the incoming stream.

You can do this by adding a layer that reads the input into the buffer and then releases one line each time it sees \r\n in the input stream.

As an aside, if you can change the stream data to have only one delimiter character (for example, only \n ), the buffering code may become a little simpler.

+4
source

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


All Articles