【问题标题】:Signal-R Calling another server method after receiving previous call dataSignal-R 在接收到先前的调用数据后调用另一个服务器方法
【发布时间】:2019-10-16 00:59:55
【问题描述】:

我正在阅读有关 Signal-R 的 Microsoft 教程,并希望在 .Net Core 中使用它而不是 Ajax,考虑到 Microsoft 的以下代码,在从在 broadcastMessage 函数中第一次调用(即定义为 javascript 函数)?

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub. 
        var chat = $.connection.chatHub;
        // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (name, message) {
            // Html encode display name and message. 
            var encodedName = $('<div />').text(name).html();
            var encodedMsg = $('<div />').text(message).html();
            // Add the message to the page. 
            $('#discussion').append('<li><strong>' + encodedName
                + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val(prompt('Enter your name:', ''));
        // Set initial focus to message input box.  
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                // Call the Send method on the hub. 
                chat.server.send($('#displayname').val(), $('#message').val());
                // Clear text box and reset focus for next comment. 
                $('#message').val('').focus();
            });
        });
    });
</script>

这样我们就可以检查接收到的数据并有条件地发起另一个调用。 或者,如果所有服务器调用都应该放在 $.connection.hub.start().done(function () {?

【问题讨论】:

    标签: .net-core signalr


    【解决方案1】:

    您可以在收到消息后调用其他方法,如下所示:

    TypeScript 示例:

    //Start connection with message controller
      public startConnectionMessage = () => {
        this.hubMessageConnection = new signalR.HubConnectionBuilder()
          .configureLogging(signalR.LogLevel.Debug)
          .withUrl('http://localhost:20000/notifications')
          .build();
    
        this.hubMessageConnection
          .start()
          .then(() => {
            //after connection started
            console.log('Notifications Service connection started!');
    
            // Start the Group Listener.
            this.addTranferGroupMessageListener();
    
            // Get ConnectionID.
            this.GetConnectionID();
    
          })
          .catch(err => console.log('Error while starting connection: ' + err))
      }
    
    // Group channel listner.
      public addTranferGroupMessageListener = () => {
        this.hubMessageConnection.on("groupMessage", (data: any) => {
          console.log(data);
        });
      }
    
      private GetConnectionID() {
        this.hubMessageConnection.invoke("GetConnectionID")
          .then((connectionID: string) => {
            console.log("Recived connectionID = " + connectionID);
    
            // call the method to register AppContextData.
            this.sendApplicationContextData(connectionID)
    
          }).catch((error: Error) => {
            console.log("Error: " + error);
          })
      }
    
    private sendApplicationContextData(connectionID: string) {
        // add the received connectionID to the payload.
        this.connection.ConnectionID = connectionID;
    
        console.log("Sending ApplicationData.");
        console.log(this.connection);
    
        //inovke server side method to pass AppContext data.
        this.hubMessageConnection.invoke("RegisterAppContextData", this.connection)
          .then()
          .catch((error: Error) => {
            console.log("Error: " + error);
          });
      }
    

    您可以看到,在建立连接后,我调用了一个集线器方法,该方法只返回一个 connectionID,并根据 connectionID 调用另一个发送该参数的方法。服务器端集线器方法是:

    public string GetConnectionID()
    {
      return this.Context.ConnectionId;
    }
    
    public async Task RegisterAppContextData(AppContextData data)
    {
        // Calls the groups Manager.
        await this.MapClientToGroups(data);
    }
    

    【讨论】:

    • 在此之前我发现另一个stackoverflow帖子非常清楚:stackoverflow.com/questions/15066693/…我认为解决方案是:function doSomething { if ($.connection.hub.state === $.signalR.connectionState.disconnected ) { $.connection.hub.start().done(function () { myHub.server.myHubMethod(); }); } else { myHub.server.myHubMethod(); } }
    • @mz1378 但在这种情况下,您在连接状态下调用方法。但也许它对你有用:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2018-05-29
    相关资源
    最近更新 更多