admin管理员组

文章数量:1424910

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?

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?

Share Improve this question edited Dec 25, 2015 at 10:59 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 7, 2012 at 15:47 GugisGugis 53912 silver badges25 bronze badges 3
  • What character separates the two pieces? A New line? You have no control over the packets themselves. – loganfsmyth Commented May 7, 2012 at 15:52
  • AS3 code: server.send("setUser|"+name_txt.text)+"\n"; server.send("joinChannel|aha")+"\n"; – Gugis Commented May 7, 2012 at 22:02
  • Did you try my answer? Also, the code in your ment won't put newlines in the data sent, it appends a newline to the result of the send mand... – loganfsmyth Commented May 8, 2012 at 5:55
Add a ment  | 

1 Answer 1

Reset to default 3

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 es in, then you would do the splitting in the data callback and keep track of any leftover partial mands 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;
    }
  });
});

本文标签: javascriptNodeJS socket data splittingStack Overflow