Как исправить ошибку «Uncaught Reference Error: автобан не определен в HelloworldProxy.connect»? - PullRequest
1 голос
/ 10 октября 2019

Я пытаюсь внедрить Franca IDL с помощью js и autobahn на клиентской стороне и сервере wamp c ++. Я совершенно новичок в этом .js Я впервые работаю над этим, но я работал над franca с D-bus, такУ меня есть идея о Франке. Любая помощь и предложения очень помогут.

В клиентской среде я написал простой код helloworld

package example.hello
  interface HelloWorld {
  version {major 1 minor 0}
  method sayHello {
    in {
      String name
    }
   out {
     String message
   }
  }
} 

и сгенерировал код привязки autobahn js. Теперь я беру код, показанный ниже, но он показывает следующую ошибку: «Uncaught ReferenceError: autobahn не определен в HelloworldProxy.connect»

hello.html code:

         <form>
   <br/><br/><br/>
        <label>Result: <output id="message" /></label><br/>
              <br/><hr/><br/><br/>

      <label>Status: <output id="connectionStatus"></output></label>
     </form>
         <p>This example uses WAMP communication to interact with a C++ 
    server using CommonAPI.</p>
      <br/><br/><br/><hr/>
     <form> 
<br/><br/><br/>
    <label>Result: <output id="message" /></label><br/>
            <br/><hr/><br/><br/>

    <label>Status: <output id="connectionStatus"></output></label>
</form>


 <script src="js/HelloworldProxy.js"></script>
<!--script src="js/HelloworldClientBlueprint.js"></script>-->
<script type="text/javascript">
         console.log("I am alive!");
var proxy = new HelloworldProxy();
proxy.connect('ws://localhost:8081');
            //var clientId = 66;
    //var addr = 
'local:example.hello.helloworld:v0_1:example.hello.helloworld';

proxy.onOpened = function() {
    // your code goes here
 connection.onopen = function(session, details) {
            console.log("Connected", details);
            setStatus("Connected to network.");
};

  /**
  * Async callback in response to a 'sayHello' call.
   * 
   * @param cid the call id
   * @param message
    */
    proxy.replySayHello = function(cid, message) {
    // your code goes here
    };


/**
 * API function provided by the proxy for calling method 'sayHello'.
 * @param name
  */
    proxy.sayHello(name);


};

proxy.onClosed = function(event) {
// your code goes here
            connection.onclose = function(reason, details) {
            console.log("Connection closed", reason, details);
            setStatus("Disconnected.");
         }

};
setStatus("Connecting to server...");
         connection.open();
         function setStatus(text) {
            document.getElementById("connectionStatus").value = text;
         }

      </script>



  </body>
</html>

generated autobahn binding code:

function HelloworldProxy() {
    this.connection = null;
    this.session = null;
    this.address = 
"local:example.hello.helloworld:v0_1:example.hello.helloworld"
    this.callID = 0;
}

HelloworldProxy.prototype.getNextCallID = function() {
    this.callID = this.callID + 1;
    return this.callID;
};

  // call this method to invoke sayHello on the server side
       HelloworldProxy.prototype.sayHello = function(name) {
         var cid = this.getNextCallID();
         var _this = this;
       this.session.call(this.address + '.sayHello', [cid, name]).then(
        function (res) {
           if (typeof(_this.replySayHello) === "function") {
            _this.replySayHello(cid, res);
            }
       },
        function (err) {
            console.log("Call failed, error message: ", err);
            _this.replyError();
        }
    );
    return cid;
};

  HelloworldProxy.prototype.connect = function(address) {
     var _this = this;

_this.connection = new autobahn.Connection({
    url: address,
    realm: 'realm1'}
);

_this.connection.onopen = function(session, details) {
    console.log("Connected", details);
    if (typeof(_this.onOpened) === "function") {
        _this.onOpened();
    }

    _this.session = session;

    // subscribing to all broadcasts
}

_this.connection.onclose = function(reason, details) {
    console.log("Connection closed", reason, details);
    if (typeof(_this.onClosed) === "function") {
        _this.onClosed(reason);
    }
}

setStatus("Connecting to server...");
_this.connection.open();

     };

Мне нужносоединить клиента с сервером и получить ответное сообщение от сервера. Сервер работает хорошо, я проверил его с помощью RESTClint.sh.

Ответы [ 2 ]

1 голос
/ 22 октября 2019

привет, это сработало. Я просто добавил функции отображения в js и получил вывод. аналогично приведенному ниже коду:

          document.getElementById("i1").onclick = function(){
          console.log("sending " + Indicator.R_ind);
          proxy.Myindicator(Indicator.name);

         proxy.replySayHello = function(cid, message) {
         document.getElementById("message").value = message;
         document.getElementById("d1").innerHTML = message;
         };
0 голосов
/ 10 октября 2019

Я обошел вокруг и получил решение по вышеуказанному вопросу. Я фактически пропустил файл autobahn.min.js (заголовочный файл) из автобана. связь была достигнута. Потребовалось полдня, чтобы достичь этой стадии, но это был хороший опыт.

Теперь проблема в том, что я не понимаю, как вызвать метод sayhello в javascript, чтобы получить разрешение с сервера. То есть: в части javascript у меня есть

                 /**
                   * Async callback in response to a 'sayHello' call.
                   * 
                   * @param cid the call id
                   * @param message
                     */
                          proxy.replySayHello = function(cid, message) {
                              // your code goes here
                            };


        /**
     * API function provided by the proxy for calling method 'sayHello'.
       * @param name
     */
       proxy.sayHello(name);

Я не понимаю, как вызывать эти функции, любые предложения мне очень помогут. Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...