Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS socket data splitting

NodeJS socket data splitting

Problem

When I need to split data I have to convert it to string.
Here is my data handler function:

  socket.on('data', function (data) {
    var str = data.toString().split("|");
    switch(str[0]){
        case "setUser":
        setUser(str[1], socket);
        break;
        case "joinChannel":
        joinChannel(str[1], socket);
        break;
    }

  });

When I send data like "setUser|Name" and then "joinChannel|main" from AS3 client. NodeJS reads it as one data packet.
My question is how to make that as two different data packets?

Problem courtesy of: Gugis

Solution

Normally you would buffer all of the data together, and then parse it as one string. Or if you need to part it as it comes in, then you would do the splitting in the data callback and keep track of any leftover partial commands to prepend on the net chunk received.

var data = '';
socket.setEncoding('utf8');
socket.on('data', function(chunk) {
  data += chunk;
});
socket.on('end', function() {

  var lines = data.split('\n');
  lines.forEach(function(line) {
    var parts = line.split('|');
    switch (parts[0]) {
      case 'setUser':
        setUser(str[1], socket);
        break;
      case 'joinChannel':
        joinChannel(str[1], socket);
        break;
    }
  });
});
Solution courtesy of: loganfsmyth

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS socket data splitting

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×