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?
- 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;
}
});
});
本文标签: javascriptNodeJS socket data splittingStack Overflow
版权声明:本文标题:javascript - NodeJS socket data splitting - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745438817a2658351.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论