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?
- 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
1 Answer
Reset to default 3Normally 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;
}
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745438817a4627735.html
评论列表(0条)