简体   繁体   English

从 websocket 接收似乎是封装的 JSON 的内容。 我如何处理这种格式?

[英]Receiving what appears to be encapsulated JSON from websocket. How do I handle this format?

Every received message starts with a number followed by what appears to be encapsulated JSON.每条收到的消息都以一个数字开头,后跟似乎是封装的 JSON 的内容。

JSON.parse() obviously doesn't work here. JSON.parse()显然在这里不起作用。

0{"sid":"ZH4b_LP4asdas","upgrades":[],"pingInterval":25000,"pingTimeout":5000}
40
42["request","{\"api_key\":\"blablabla\",\"version\":2,\"step\":{\"type\":\"CATCHER\",\"params\":{},\".......\"}"]
3
3 .......

Does this data format has some common name or specification and how do I go about decoding it?这种数据格式是否有一些通用名称或规范,我该如何解码?

PS: I'm using node.js ws websocket and have to send "2" pings in order to maintain the connection. PS:我正在使用 node.js ws websocket 并且必须发送“2”ping 以保持连接。

Done it the crude way.用粗暴的方式完成了。 You would be wrong to assume I couldn't.如果你认为我不能,那就错了。 But if there is another way, let me know!但如果有其他方法,请告诉我! :) :)

EDIT : of course, had to add strip slashes as well for the actual data.编辑:当然,必须为实际数据添加斜杠。

function stripslashes(str) {
    str = str.replace(/\\'/g, '\'');
    str = str.replace(/\\"/g, '"');
    str = str.replace(/\\0/g, '\0');
    str = str.replace(/\\\\/g, '\\');
    return str;
}

var data= '0{"sid":"ZH4b_LP4asdas","upgrades":[],"pingInterval":25000,"pingTimeout":5000}'
var match = data.match(/^\d+/);
if (!match) {console.log('corrupted data'); return}
var channel = match[0]; //channel
var message = data.slice(match[0].length);
if (!message) {console.log('empty message'); return}
message=message.replace(/^\[.*?,"|"\]$/g, "");  //extracting from array formation
message=stripslashes(message);
data=JSON.parse(message);
console.log(data);  //log the data
if (typeof data.step != 'undefined' && typeof data.step.data != 'undefined' && typeof data.step.data.body != 'undefined')
console.log(Buffer.from(data.step.data.body,'base64').toString());  //extract base64 body of the message within

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM