订阅相同主题创建异常行为

时间:2016-03-19 16:54:24

标签: activemq mqtt

如果我一次又一次订阅同一主题,是否有任何问题。我有一个话题chatWith/u31我觉得当我重新启动我的应用程序订阅同一主题时,mqtt会产生一些问题,如:

任何一条消息都没有发送到一方,或者消息没有被接收到另一方,这两条消息都被传送到&抵达后,客户端断开连接

以下是使用paho的客户端代码,代理商为activemq

$(document).ready(function(){
  var myUserId = "u56";
  var statusTopic = "UserStatus/"+myUserId;
  $("#connect_clientId").val("example-"+(Math.floor(Math.random() * 100000)));
  if( !window.WebSocket) {
    $("#connect").html("\
        <h1>Get a new Web Browser!</h1>\
        <p>\
        Your browser does not support WebSockets. This example will not work properly.<br>\
        Please use a Web Browser with WebSockets support (WebKit or Google Chrome).\
        </p>\
    ");
  } else {

    var client, destination;

    $('#connect_form').submit(function() {
      var host = $("#connect_host").val();    
      var port = $("#connect_port").val();
      var clientId = $("#connect_clientId").val();
      var user = $("#connect_user").val();
      var password = $("#connect_password").val();

      destination = $("#destination").val();


      client = new Messaging.Client(host, Number(port), clientId);

      client.onConnect = onConnect;

      client.onMessageArrived = onMessageArrived;
      client.onMessageDelivered = onMessageDelivered;
      client.onConnectionLost = onConnectionLost;            

      client.connect({
        userName:user, 
        password:password, 
        onSuccess:onConnect, 
        onFailure:onFailure
      }); 
      return false;
    });  


  function createByteMessage(payload, destination) {
    var enc = stringToUint(JSON.stringify(payload));
    var message = new Messaging.Message(uintToString(enc)); 
    message.destinationName = destination;
    return message;    
  }

    var onConnect = function(frame) {
      debug("connected to MQTT");
      $('#connect').fadeOut({ duration: 'fast' });
      $('#connected').fadeIn();
      var message = createByteMessage({
        id: 'USER_STATUS',
        'status': 'Online',
        'sender': myUserId
      }, statusTopic);
      message.retained = true;
      client.send(message);       
      client.subscribe(destination);

    };  

    // this allows to display debug logs directly on the web page
    var debug = function(str) {
      $("#debug").append(document.createTextNode(str + "\n"));
    };  

    $('#disconnect').click(function() {
      client.disconnect();
      $('#connected').fadeOut({ duration: 'fast' });
      $('#connect').fadeIn();
      $("#messages").html("")
      return false;
    });

    $('#send_form').submit(function() {
      var text = $('#send_form_input').val();
      if (text) {
        var payload = {
          'id': Math.floor(Math.random()*10000+1),
          'text': text,
          'time': new Date(),
          'sender': '111',
          'senderName': 'currentUser.name'
        };
        var enc = stringToUint(JSON.stringify(payload));
        var message = new Messaging.Message(uintToString(enc));   
        message.destinationName = destination;
        client.send(message); 


        $('#send_form_input').val("");
      }
      return false;
    });

  function stringToUint(string) {
      var string = btoa(unescape(encodeURIComponent(string))),
          charList = string.split(''),
          uintArray = [];
      for (var i = 0; i < charList.length; i++) {
          uintArray.push(charList[i].charCodeAt(0));
      }
      return new Uint8Array(uintArray);
  }

  function uintToString(uintArray) {
      var encodedString = String.fromCharCode.apply(null, uintArray),
          decodedString = decodeURIComponent(escape(atob(encodedString)));
      return decodedString;
  }    

    function onFailure(failure) {
      debug("failure");
      debug(failure.errorMessage);
    }  

    function onMessageDelivered(message) {
      console.log("onMessageDelivered: "+message.payloadString);
    }

    function onMessageArrived(message) {
      console.log("onMessageArrived: "+message.payloadString);
      var p = document.createElement("p");
      var t = document.createTextNode(message.payloadString);
      p.appendChild(t);
      $("#messages").append(p);
    }

    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        debug(client.clientId + ": " + responseObject.errorCode + "\n");
      }
    }    

  }
});    

问题是如果运行具有相同destination主题的应用程序,并且statusTopic应用程序异常正常工作。但每次如果我以不同的订阅方式启动应用程序,它都能正常运行。

0 个答案:

没有答案