Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate TCP socket messages in node.js

I'm cutting my teeth with TCP sockets and am confused with how messages are arriving to my app. Seems like they are broken up. Anyone know how I can best join them back 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));
});

Sample of what dumps to the console looks like:

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 stuff up at the linebreak so I dont have incomplete messages. Is there a way to tell node to do this for me? If not, does anyone have any samples of how this might be done?

like image 813
Anthony Webb Avatar asked Dec 25 '11 01:12

Anthony Webb


1 Answers

I found a module called "carrier" which does exactly what I needed. 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

like image 152
Anthony Webb Avatar answered Sep 28 '22 19:09

Anthony Webb