前言:
mqtt(Message Queuing Telemetry Transport),pomelo不是支持了么,闲来没事看到有中文文档想撸一发,没想到活活被气死。。。
正文:
传送门 https://mcxiaoke.gitbooks.io/mqtt-cn/content/mqtt/0301-CONNECT.html
const net = require('net');
let server = net.createServer();
server.on('connection', function(sock) {
sock.on('data', function(data) {
console.log(data.toString())
let index=0
let frame={
packetType: (data[index]>>4)&0xF,
flags:(data[index++]&0x2<<4)&0xF,
remaining:getRemain(),
variableHeader:{
protocolName:(data.slice(index+2,index+6).toString()),
protocolLevel:(data[index+7]),
connectFlags:data[index+8]&&0xff,
keepAlive:data.slice(index+9,index+13)
}
}
function getRemain() {
let byteLength=1;
let value=0;
do{
value+=byteLength*(data[index]&0x7f)
index++
byteLength *= 128
} while ((data[index]&0x80)==0x80)
if(byteLength>Math.pow(128,3)){
throw Error("剩余长度字段异常")
}
return value
}
console.log(frame,index)
const array=[];
array.push('0X20','0X2')
const buf=Buffer.from(array)
});
});
server.listen(1883);
//打印
{ protocolName: 'MQTT',
protocolLevel: 194,
connectFlags: 0,
keepAlive: <Buffer 3c 00 10 61> } }
protocolLevel,和connectFlags匹配不上,直接炸了。协议版本匹配不上最奇葩,已经疯了找不到bug,准备自杀。

