mqttws31.js接收中文内容时出现AMQJS0009E Malformed UTF data:a9 -5e ., Stack trace: Error

AMQJS0005E Internal error. Error Message: AMQJS0009E Malformed UTF data:a9 -5e ., Stack trace: Error: AMQJS0009E Malformed UTF data:a9 -5e .
    at parseUTF8 (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:639:12)
    at Message._getPayloadString (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:2074:12)
    at Message.get payloadString [as payloadString] (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:2122:37)
    at ClientImpl.onMessageArrived (http://127.0.0.1/onlineqs/front/call/scripts/mqttUtil.js:54:31)
    at ClientImpl.Paho.MQTT.ClientImpl._receiveMessage (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:1399:9)
    at ClientImpl.Paho.MQTT.ClientImpl._receivePublish (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:1374:10)
    at ClientImpl.Paho.MQTT.ClientImpl._handleMessage (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:1250:10)
    at ClientImpl.Paho.MQTT.ClientImpl._on_socket_message (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:1151:12)
    at WebSocket. (http://127.0.0.1/onlineqs/front/call/scripts/mqttws31.js:157:13)

 

解决办法:

服务端:将中文转utf-8后发送

客户端:

function onMessageArrived(message) {

    var receiveStr=byteToString(message.payloadBytes);
    //var receiveStr=message.payloadString;
    console.log("到达的信息:"+receiveStr);
}

 

function byteToString(arr) {
    if(typeof arr === 'string') {
        return arr;
    }
    var str = '',
        _arr = arr;
    for(var i = 0; i < _arr.length; i++) {
        var one = _arr[i].toString(2),
            v = one.match(/^1+?(?=0)/);
        if(v && one.length == 8) {
            var bytesLength = v[0].length;
            var store = _arr[i].toString(2).slice(7 - bytesLength);
            for(var st = 1; st < bytesLength; st++) {
                store += _arr[st + i].toString(2).slice(2);
            }
            str += String.fromCharCode(parseInt(store, 2));
            i += bytesLength - 1;
        } else {
            str += String.fromCharCode(_arr[i]);
        }
    }
    return str;
}

 

参考:https://stackoverflow.com/questions/25547653/receive-binary-with-paho-mqttws31-js

 

 

你可能感兴趣的:(mqttws31.js接收中文内容时出现AMQJS0009E Malformed UTF data:a9 -5e ., Stack trace: Error)