NodeJS socket data splitting

2020-06-23 09:01发布

问题:

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?

回答1:

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;
    }
  });
});