Signal-R收到先前的呼叫数据后,呼叫另一个服务器方法

时间:2019-10-09 20:46:49

标签: .net-core signalr

我正在阅读有关Signal-R的Microsoft教程,并希望使用它代替.Net Core中的Ajax,考虑到Microsoft的以下代码,在从Windows接收到数据后,有什么方法可以进行另一个服务器调用 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(){?

1 个答案:

答案 0 :(得分:0)

您可以在收到消息后像这样调用其他方法:

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);
}