【问题标题】:Signalr Close Connection信号器关闭连接
【发布时间】:2021-05-13 22:43:47
【问题描述】:

我正在尝试在我的 web 应用程序中创建一个停止按钮。 webapp 为不同的文件创建批量快捷方式。我尝试过使用$.connection.shortcutHub.stop(),但是这会出现错误提示Cannot read property 'shortcutHub' of undefined(anonymous function)

代码如下。单击stop 按钮后,我需要停止连接。停止按钮的 id 是stopButton

        $(document).ready(function () {
        // initialize the connection to the server
        var progressNotifier = $.connection.shortcutHub;

        // client-side sendMessage function that will be called from the server-side
        progressNotifier.client.sendMessage = function (message, percent) {
            // update progress
            UpdateMessage(message, percent);
        };

        progressNotifier.client.redo = function () {
            redo();
        };

        progressNotifier.client.success = function () {
            success();
        };

        progressNotifier.client.fail = function () {
            fail();
        };


        // establish the connection to the server and start server-side operation
        $.connection.hub.start().done(function () {
            $('#confirmbutton').click(function () {
                jQuery.noConflict();
                document.getElementById('closeButton').setAttribute("class", "btn btn-default hidden");
                $('#myModal').modal('show');
                //document.getElementById('confirmbutton').disabled = true;
                //document.getElementById('barcodepanel').setAttribute("class", "panel panel-default");
                var ticket = getCookie('ticket');
                var path = getCookie('CBSShortcut_Path');
                var checkeddocs = getCheckedBoxes("dcheck");
                var checkedfolders = getCheckedBoxes("fcheck");
                progressNotifier.server.createshortcuts(ticket, path, checkeddocs, checkedfolders);
            });

            $('#stopButton').click(function () {
                document.getElementById('closeButton').setAttribute("class", "btn btn-default");
                document.getElementById('confirmbutton').disabled = false;


                //What do I put here?
            });



        });



        function UpdateMessage(message, percent) {
            // get result div
            var msg = $("#result");
            // set message
            msg.html(message);
            //set value of progress bar
            document.getElementById('closeButton').setAttribute("class", "btn btn-default hidden")
            $('#progressbar').css('width', percent + '%').attr('aria-valuenow', percent);
        }

        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1);
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
            return "";
        }

        function redo() {
            document.getElementById('confirmbutton').disabled = false;
            jQuery.noConflict();
            $('#myModal').modal('hide');
        }


        // Pass the checkbox name to the function
        function getCheckedBoxes(chkboxclass) {
            var checkboxes = document.getElementsByClassName(chkboxclass);
            var checkboxesChecked = [];
            var ids = "";
            // loop over them all
            for (var i = 0; i < checkboxes.length; i++) {
                // And stick the checked ones onto an array...
                if (checkboxes[i].checked) {
                    checkboxesChecked.push(checkboxes[i]);
                    ids = ids + checkboxes[i].getAttribute("Name") + ",";
                }
            }
            // Return the array if it is non-empty, or null
            //return checkboxesChecked.length > 0 ? checkboxesChecked : null;
            return ids;
        }
    }
);`

感谢任何帮助。我已经尝试了 google 提供的所有方法(主要是 stackoverflow 网站),但我仍然遇到同样的问题。

【问题讨论】:

    标签: javascript signalr signalr-hub


    【解决方案1】:

    你试过了吗:

    $.connection.hub.stop().done(function() {
        alert('stopped');
    });
    

    它会起作用的。

    【讨论】:

    • 我会把这个放在哪里?我在几个地方尝试过,但我一直收到同样的错误。
    • ok.. 当您开始连接时,将 $.connection 保留在一个变量中,然后使用该变量来停止它,就像这样 - var ChatConnection=$.connection;当你想停止时,只需使用 ChatConnection.stop();注意:- 保持变量为全局变量。
    • 我已将progressNotifier 分配为保存连接的全局变量。当我输入progressNotifier.stop(); 时,它告诉我它不是一个函数。
    • 哦,对不起,使用 progressNotifier.hub.stop();我忘了添加集线器
    • Uncaught TypeError: Cannot read property 'stop' of undefined
    【解决方案2】:

    您想使用全局 SignalR Hub 客户端连接,因为集线器共享单个连接(也不要使用 progressNotifier 对连接进行任何操作,仅用于侦听和发送事件。)

    您的测试代码可能如下所示:

     $('#stopButton').click(function () {
                    document.getElementById('closeButton').setAttribute("class", "btn btn-default");
                    document.getElementById('confirmbutton').disabled = false;
    
    
                    $.connection.hub.stop();
                    //try to send a server event. Will throw an error 
                    //Uncaught Error: SignalR: Connection must be started before data can be sent. Call .start() before .send()
                });
    

    【讨论】:

    • 我收到Uncaught TypeError: Cannot read property 'hub' of undefined
    • 如果您的代码与问题中的位置完全相同,您能否在控制台中粘贴带有错误的屏幕截图?
    • 有趣。您能否将$("#stopbutton").click() 代码移出$.connection.hub.start().done(...) 代码块,看看是否能解决问题?
    • 我得到了同样的错误。 IntelliSense 不建议在其中任何一个位置停止。当我在$('#confirmbutton').click(function () { } 中输入它时,它确实建议停止
    • 您使用的是什么版本的 SignalR?我几乎逐字复制了您的代码,一切正常。
    【解决方案3】:

    这是我正在使用的工作代码:

    let connection;  
    let connectionUrl = 'https://someurl/hubEndpoint';
    
    connection = new signalR.HubConnectionBuilder()
        .withUrl(connectionUrl)
        .build();
    
    connection.serverTimeoutInMilliseconds = 60 * 10000;
    
    connection.on("ReceiveMessage", (message) => {                
        console.log(message);     
        // to do appropriate coding
    });
    
    connection.start().then(function () {
        console.log('Connected to server');
        subject = new signalR.Subject();           
    });
    
    setTimeout(() => {
        connection.stop().then(function() {
            console.log('Closed');
            connection = null;    
        });
    }, (2000)); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 2020-05-09
      • 2016-08-10
      相关资源
      最近更新 更多