mqttjs / mqtt-packet

Parse and generate MQTT packets like a breeze in JS
Other
206 stars 93 forks source link

Are there any usage examples? #135

Open mStirner opened 1 year ago

mStirner commented 1 year ago

I try to connect to my mosquitto broker. The problem im facing, as soon as the "connect" package is writen, the tcp socket is closed. I guess this happens because the package is invalid/the broker expect something else?

Code i used for testing:

const net = require("net");

const mqtt = require("mqtt-packet");
const parser = mqtt.parser({
    protocolVersion: 4
});

const socket = net.Socket();

socket.on("close", () => {
    console.log("connection closed");
});

socket.on("data", (data) => {

    console.log(">", data);

    parser.once('packet', packet => {
        console.log(packet)
    });

    parser.parse(data);

});

socket.on("connect", () => {

    console.log("Connected to tcp://open-haus.lan:1883");

    let data = mqtt.generate({
        cmd: 'connect',
        protocolId: 'MQTT', // Or 'MQIsdp' in MQTT 3.1 and 5.0
        protocolVersion: 4, // Or 3 in MQTT 3.1, or 5 in MQTT 5.0
        clean: true, // Can also be false
        clientId: 'my-device-test-node',
        //keepalive: 0, // Seconds which can be any positive number, with 0 as the default setting
        will: {
            topic: '#',
            payload: Buffer.from('dead'), // Payloads are buffers
        }
    });

    socket.write(data, () => {
        console.log("connect has writen", data)
    });

});

socket.connect(1883, "open-haus.lan");

Output:

Connected to tcp://open-haus.lan:1883
connect has writen <Buffer 10 28 00 04 4d 51 54 54 04 06 00 00 00 13 6d 79 2d 64 65 76 69 63 65 2d 74 65 73 74 2d 6e 6f 64 65 00 01 23 00 04 64 65 61 64>
connection closed

The "data" event on the tcp socket isnt even fired.

As seen in this graphic, after the tcp socket is established, a connect packet is send to the broker: grafik

I dont get anything back.