如果客户端发送JSON,我的TCP套接字数据处理程序在try块中工作正常。但是,我也想通过telnet支持一些基本的“终端命令”,所以如果解析器失败,catch块应该尝试识别一个受支持的块,但我总是得到默认的响应SyntaxError ......
socket.on('data', function(data){
try{
var json = JSON.parse(data);
switch(json.event){
default:
console.log('unhandled event:'+json.event);
break;
}
}catch(err){
console.log("CLIENT SAID: "+data);
switch(data){
case "echo":
socket.write("ECHO:"+data+"\n");
break;
case "clients":
socket.write("CLIENTS:"+clients.length+"\n");
break;
default:
socket.write('ERROR:'+err+"\n");
break;
}
}
});
答案 0 :(得分:2)
您不接受完整回复。您应该从流中收集数据并等到end
事件,直到数据完全被接收为止。
var body = '';
socket.setEncoding('utf8');
socket.on('data', function(data) {
body += data;
});
socket.on('end', function () {
try {
var json = JSON.parse(body);
switch (json.event) {
default: console.log('unhandled event:' + json.event);
break;
}
} catch (err) {
console.log("CLIENT SAID: " + body);
switch (data) {
case "echo":
socket.write("ECHO:" + body + "\n");
break;
case "clients":
socket.write("CLIENTS:" + clients.length + "\n");
break;
default:
socket.write('ERROR:' + err + "\n");
break;
}
}
});