断开连接时重新连接 stomp

Reconnect stomp when disconnected

我正在使用以下代码 create/subscribe 到主题并处理消息。有时连接丢失并且错误显示:

Whoops! The connection was lost...

我想知道有没有办法重新连接。是否可以在错误回调中或在方法中定义整个代码并在错误回调中递归调用它?

 $(document).ready(function () {
  ........
  ...............
      try {
            var socket = new SockJS("${createLink(uri: '/stomp')}");
            var client = Stomp.over(socket);
            client.connect({}, function () {
            client.subscribe("/topic/${userInstance?.username}",                 
            function (message) {
           ............
           ....................

              });
            });
        } catch (error) {
            console.log("ERROR: " + error.toString());
        }
   });

我设法使用失败回调完成了它并再次连接。只要失败,它就会一直尝试。

这是我在 Polymer 元素中使用的:

ready: function() {
    this.connectWs();
},
connectWs: function() {
    this.socket = new WebSocket(this.socketUrl);
    this.stompClient = Stomp.over(this.socket);
    this.stompClient.debug = null;
    this.stompClient.connect({},
        function(frame) {
            // Connection OK
        }.bind(this),
        function(e) {
            console.error(e, "Reconnecting WS", this.socketUrl);
            window.setTimeout(function() {
                this.connectWs();
            }.bind(this), 2500);
        }.bind(this)
    );
},