eclipse / paho.mqtt.javascript

paho.mqtt.javascript
Other
1.14k stars 468 forks source link

client.send results in "Cannot read property 'length' of undefined" TypeError #162

Open Sunchild81 opened 6 years ago

Sunchild81 commented 6 years ago

Hi all,

In my onConnect cb I'm simply trying to send a "Hello" message on the topic I subscribed to just before I send it. However, for some reason it's giving me a TypeError: Cannot read property length of undefined, which point me to this section:

    /**
     * Called when the underlying websocket has received a complete packet.
     * @ignore
     */
    ClientImpl.prototype._on_socket_message = function (event) {
        this._trace("Client._on_socket_message", event.data);
        var messages = this._deframeMessages(event.data);
        for (var i = 0; i < messages.length; i+=1) {
            this._handleMessage(messages[i]);
        }
    };

So messages is undefined apparently. I'm hoping somebody encountered this before or could point me in the right direction. Or perhaps it's a bug, but seems unlikely since nobody's having this issue as of yet.

I'm using React 15.4.1 with WebPack and npm package paho-mqtt 1.0.4 I thought it might be related to below issue 150. However the proposed solution didn't help me: https://github.com/eclipse/paho.mqtt.javascript/issues/150

What I'm doing is real straightforward:

        this.client.connect(
            {   
                userName: this.userName, 
                password: this.password, 
                useSSL: true,
                onSuccess: this.onConnect.bind(this), 
                onFailure: this.showConnectionErrorMessage, 
                willMessage: this.lastWill 
            }
        );

And my onConnect handling:

    onConnect() {
        console.log('onSucces');
        this.client.subscribe(this.broadcastTopic);
        this.client.onMessageArrived = this.onMessageArrived;

        // I tried setting a timeout on my first attempt
        // setTimeout( () => {
            let message = new Paho.Message("Hello");
            message.destinationName = this.broadcastTopic;

            this.client.publish(message);
            // I also tried the direct way of sending a message
            // this.client.send(this.broadcastTopic, 'World')
        // }, 3000)
    },
    onMessageArrived(message) {
        console.log('onMessageArrived');
        console.log(message);
    },

Thanks all!

gleb-svechnikov commented 5 years ago

I get same error with React(create react app). However if I plug paho-mqtt with pure JS it works as expected.

AdamChrist commented 5 years ago

I get same error. I found the error caused by

var message = new Paho.MQTT.Message(input.subarray(pos, endPos));

it can be fix by this:

import PahoMQTT from 'paho-mqtt'
global.Paho = {
  MQTT: PahoMQTT
}
cgx2211 commented 5 years ago

I worked on this all day, I love you! @AdamChrist