【SignalR學習系列】6. SignalR Hubs Api 詳解(C# Server 端)


如何注冊 SignalR 中間件

為了讓客戶端能夠連接到 Hub ,當程序啟動的時候你需要調用 MapSignalR 方法。

下面代碼顯示了如何在 OWIN startup 類里面定義 SignalR Hubs 路由。

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(MyApplication.Startup))]
namespace MyApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }

    }
}

 

The /signalr URL

默認情況下,客戶端都是通過 "/signalr" 路由地址來連接到你的 Hub,你也可以修改不使用默認的 "/signalr"。

服務端代碼指定Url

app.MapSignalR("/signalrTest", new HubConfiguration());

JavaScript 客戶端代碼指定Url

<script src="signalrTest/hubs"></script>

var chat = $.connection.chatHub;
chat.url = "/signalrTest";

 .NET 客戶端代碼指定Url

var Connection = new HubConnection("http://localhost:8080/signalrTest");

 

如何創建並使用 Hub 類

為了創建 Hub 類,你需要創建一個繼承於 Microsoft.Aspnet.Signalr.Hub 的類

public class ContosoChatHub : Hub
{
    public void NewContosoChatMessage(string name, string message)
    {
        Clients.All.addNewMessageToPage(name, message);
    }
}

 

JavaScript 端的 Hub 名字

Server (駝峰命名法,第一個字母可以為大寫也可以為小寫)

public class ContosoChatHub : Hub

JavaScript (不管 Server 端第一個字母為大小還是小寫,JavaScript 客戶端必須是小寫,不然就找不到對應的 Hub)

var contosoChatHubProxy = $.connection.contosoChatHub;

 當使用 特性 HubName命名 Hub 的名字,那么 Server 端和 Client 端的 Hub 名大小寫必須保持一致。

 Server (如果 HubName 指定的第一個字母為大寫,那么 JavaScript 端也必須為大寫。如果是小寫,那么 JavaScript 端也必須為小寫)

[HubName("PascalCaseContosoChatHub")]
public class ContosoChatHub : Hub

JavaScript 

var contosoChatHubProxy = $.connection.PascalCaseContosoChatHub;

 

強類型的 Hub

 定義一個接口 T,讓你的 Hub 類繼承於 Hub<T>,這樣就可以指定你的客戶端可以調用的方法,也可以在你的 Hub 方法里開啟代碼提示。

public class StrongHub : Hub<IClient>
{
    public void Send(string message)
    {
        Clients.All.NewMessage(message);
    }
}

public interface IClient
{
    void NewMessage(string message);
}

 

如何在 Hub 類里定義客戶端可以調用的方法

如果需要暴露一個可以在客戶端調用的方法,那么需要在 Hub 里定義一個 public 的方法,如下所示。

public class ContosoChatHub : Hub
{
    public void NewContosoChatMessage(string name, string message)
    {
        Clients.All.addNewMessageToPage(name, message);
    }
}
public class StockTickerHub : Hub
{
    public IEnumerable<Stock> GetAllStocks()
    {
        return _stockTicker.GetAllStocks();
    }
}

你可以指定方法的參數和返回類型,包含復雜類型和數組。這些數據在客戶端和服務端會使用 Json 來進行傳輸,SignalR 會自動綁定復雜類型對象和數組對象。

 

Hub 里的方法名(非客戶端方法名)

Server (駝峰命名法,第一個字母可以為大寫也可以為小寫)

public void NewContosoChatMessage(string userName, string message)

JavaScript (不管 Server 端第一個字母為大小還是小寫,JavaScript 客戶端必須是小寫,不然就找不到對應的 方法)

contosoChatHubProxy.server.newContosoChatMessage(userName, message);

使用特性 HubMethodName 指定方法名,那么 Server 端和 Client 端的 方法名大小寫必須保持一致。

Server 端

[HubMethodName("PascalCaseNewContosoChatMessage")]
public void NewContosoChatMessage(string userName, string message)

JavaScript 端

contosoChatHubProxy.server.PascalCaseNewContosoChatMessage(userName, message);

 

如何在 Hub 類中調用客戶端的方法

你可以在 Hub 類方法中使用 Clients 屬性來調用客戶端的方法

Server 端

public class ContosoChatHub : Hub
{
    public void NewContosoChatMessage(string name, string message)
    {
        Clients.All.addNewMessageToPage(name, message);
    }
}

JavaScript 端

contosoChatHubProxy.client.addNewMessageToPage = function (name, message) {
    // Add the message to the page. 
    $('#discussion').append('<li><strong>' + htmlEncode(name)
        + '</strong>: ' + htmlEncode(message) + '<li>');
};

你不能從客戶端得到一個返回值,比如 int x = Clients.All.add(1,1) 是沒有用的。

你可以給參數指定復雜類型和數組類型,如下所示。

Sever 端

public void SendMessage(string name, string message)
{
    Clients.All.addContosoChatMessageToPage(new ContosoChatMessage() { UserName = name, Message = message });
}

public class ContosoChatMessage
{
    public string UserName { get; set; }
    public string Message { get; set; }
}

JavaScript 代碼

var contosoChatHubProxy = $.connection.contosoChatHub;
contosoChatHubProxy.client.addMessageToPage = function (message) {
    console.log(message.UserName + ' ' + message.Message);
});

 

指定哪些客戶端接收信息

所有連接的客戶端

Clients.All.addContosoChatMessageToPage(name, message);

只是 Calling 的客戶端

Clients.Caller.addContosoChatMessageToPage(name, message);

所有連接的客戶端除了 Calling 的客戶端

Clients.Others.addContosoChatMessageToPage(name, message);

通過 connection ID 指定特定的客戶端

Clients.Client(Context.ConnectionId).addContosoChatMessageToPage(name, message);

通過 connection ID 排除特定的客戶端

Clients.AllExcept(connectionId1, connectionId2).addContosoChatMessageToPage(name, message);

指定一個特殊組

Clients.Group(groupName).addContosoChatMessageToPage(name, message);

指定一個特殊組,並且排除特定 connection ID 的客戶端

Clients.Group(groupName, connectionId1, connectionId2).addContosoChatMessageToPage(name, message);

指定一個特殊組,但是排除 calling

Clients.OthersInGroup(groupName).addContosoChatMessageToPage(name, message);

通過 userId 指定一個特殊的用戶,一般情況下是 IPrincipal.Identity.Name

Clients.User(userid).addContosoChatMessageToPage(name, message);

在一個 connection IDs 列表里的所有客戶端和組

Clients.Clients(ConnectionIds).broadcastMessage(name, message);

指定多個組

Clients.Groups(GroupIds).broadcastMessage(name, message);

通過用戶名

Clients.Client(username).broadcastMessage(name, message);

一組用戶名

Clients.Users(new string[] { "myUser", "myUser2" }).broadcastMessage(name, message);

 

大小寫不敏感

客戶端方法名的調用是大小寫不敏感的,比如 Clients.All.addContosoChatMessageToPage 會調用客戶端的 AddContosoChatMessageToPage, addcontosochatmessagetopage, or addContosoChatMessageToPage 這些方法。

 

異步執行

public async Task NewContosoChatMessage(string name, string message)
{
    await Clients.Others.addContosoChatMessageToPage(data);
    Clients.Caller.notifyMessageSent();
}

 

如何使用一個 string 變量作為方法名

如果你需要使用一個 string 作為方法名,那么你需要把 Clients.All (or Clients.Others, Clients.Caller, etc.)  對象賦值給 IClientProxy,然后調用它的 Invoke(methodName, args...) 方法。

public void NewContosoChatMessage(string name, string message)
{
    string methodToCall = "addContosoChatMessageToPage";
    IClientProxy proxy = Clients.All;
    proxy.Invoke(methodToCall, name, message);
}

 

管理組成員關系

Server 端

public class ContosoChatHub : Hub
{
    public Task JoinGroup(string groupName)
    {
        return Groups.Add(Context.ConnectionId, groupName);
    }

    public Task LeaveGroup(string groupName)
    {
        return Groups.Remove(Context.ConnectionId, groupName);
    }
}

客戶端

contosoChatHubProxy.server.joinGroup(groupName);
contosoChatHubProxy.server.leaveGroup(groupName);

異步執行

public async Task JoinGroup(string groupName)
{
    await Groups.Add(Context.ConnectionId, groupName);
    Clients.Group(groupname).addContosoChatMessageToPage(Context.ConnectionId + " added to group");
}

 

如何在 Hub 類里面捕獲和處理連接生命周期事件

public class ContosoChatHub : Hub
{
    public override Task OnConnected()
    {
        // Add your own code here.
        // For example: in a chat application, record the association between
        // the current connection ID and user name, and mark the user as online.
        // After the code in this method completes, the client is informed that
        // the connection is established; for example, in a JavaScript client,
        // the start().done callback is executed.
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        // Add your own code here.
        // For example: in a chat application, mark the user as offline, 
        // delete the association between the current connection id and user name.
        return base.OnDisconnected();
    }

    public override Task OnReconnected()
    {
        // Add your own code here.
        // For example: in a chat application, you might have marked the
        // user as offline after a period of inactivity; in that case 
        // mark the user as online again.
        return base.OnReconnected();
    }
}

 

如何從 Content 里面獲取 Clients 信息

Calling 客戶端的 connection ID

string connectionID = Context.ConnectionId;

connection ID 是一個由SignalR分配的 GUID  ( 你不能用自己的代碼指定 ). 每個連接都有一個 connection ID , 如果你的應用里包含多個 Hubs,那么多個 Hubs也會共用同一個 connection ID .

Http Header 數據

System.Collections.Specialized.NameValueCollection headers = Context.Request.Headers;
System.Collections.Specialized.NameValueCollection headers = Context.Headers;

Query string 數據

System.Collections.Specialized.NameValueCollection queryString = Context.Request.QueryString;
System.Collections.Specialized.NameValueCollection queryString = Context.QueryString;
string parameterValue = queryString["parametername"];

JavaScript 客戶端 QueryString

$.connection.hub.qs = { "version" : "1.0" };

這邊的 $.connection.hub.qs 不是指你當前的 Hub ($.connection.chatHub.qs)。

Cookies

System.Collections.Generic.IDictionary<string, Cookie> cookies = Context.Request.Cookies;
System.Collections.Generic.IDictionary<string, Cookie> cookies = Context.RequestCookies;

用戶信息

System.Security.Principal.IPrincipal user = Context.User;

Request 的 HttpContext 對象

System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext();

 

如何在客戶端和服務端傳遞 State

JavaScript 客戶端

contosoChatHubProxy.state.userName = "Fadi Fakhouri";
contosoChatHubProxy.state.computerName = "fadivm1";

Server 端獲取,可以使用 Caller 或者 CallerState 兩種方式

string userName = Clients.Caller.userName;
string computerName = Clients.Caller.computerName;
string userName = Clients.CallerState.userName;
string computerName = Clients.CallerState.computerName;

 

如何在 Hub 類中捕獲異常

  • 使用 try - catch 並記錄日志
  • 創建一個能處理OnIncomingError的 Hubs 管道模型
    • public class ErrorHandlingPipelineModule : HubPipelineModule
      {
          protected override void OnIncomingError(ExceptionContext exceptionContext, IHubIncomingInvokerContext invokerContext)
          {
              Debug.WriteLine("=> Exception " + exceptionContext.Error.Message);
              if (exceptionContext.Error.InnerException != null)
              {
                  Debug.WriteLine("=> Inner Exception " + exceptionContext.Error.InnerException.Message);
              }
              base.OnIncomingError(exceptionContext, invokerContext);
      
          }
      }
      
      public void Configuration(IAppBuilder app)
      {
          // Any connection or hub wire up and configuration should go here
          GlobalHost.HubPipeline.AddModule(new ErrorHandlingPipelineModule()); 
          app.MapSignalR();
      }
  • 使用 HubException 類,拋出異常
    • public class MyHub : Hub
      {
          public void Send(string message)
          {
              if(message.Contains("<script>"))
              {
                  throw new HubException("This message will flow to the client", new { user = Context.User.Identity.Name, message = message });
              }
      
              Clients.All.send(message);
          }
      }

 

啟用日志診斷

如果需要啟動 Server 端日志,那么需要在 web.config 里面添加一個 system.diagnostics 節點

<system.diagnostics>
    <sources>
      <source name="SignalR.SqlMessageBus">
        <listeners>
          <add name="SignalR-Bus" />
        </listeners>
      </source>
     <source name="SignalR.ServiceBusMessageBus">
        <listeners>
            <add name="SignalR-Bus" />
        </listeners>
     </source>
     <source name="SignalR.ScaleoutMessageBus">
        <listeners>
            <add name="SignalR-Bus" />
        </listeners>
      </source>
      <source name="SignalR.Transports.WebSocketTransport">
        <listeners>
          <add name="SignalR-Transports" />
        </listeners>
      </source>
      <source name="SignalR.Transports.ServerSentEventsTransport">
          <listeners>
              <add name="SignalR-Transports" />
          </listeners>
      </source>
      <source name="SignalR.Transports.ForeverFrameTransport">
          <listeners>
              <add name="SignalR-Transports" />
          </listeners>
      </source>
      <source name="SignalR.Transports.LongPollingTransport">
        <listeners>
            <add name="SignalR-Transports" />
        </listeners>
      </source>
      <source name="SignalR.Transports.TransportHeartBeat">
        <listeners>
            <add name="SignalR-Transports" />
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="SignalRSwitch" value="Verbose" />
    </switches>
    <sharedListeners>
      <add name="SignalR-Transports" 
           type="System.Diagnostics.TextWriterTraceListener" 
           initializeData="transports.log.txt" />
        <add name="SignalR-Bus"
           type="System.Diagnostics.TextWriterTraceListener"
           initializeData="bus.log.txt" />
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

 

如何在 Hub 類外面調用客戶端方法和管理組

如果需要在 Hub 類外面調用客戶端方法和管理組,那么需要獲取一個 SignalR context 對象,然后可以通過 context.Clients 對象來操作客戶端方法和組。

IHubContext _context = GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>();
_context.Clients.All.updateStockPrice(stock);

 

如何自定義管道模型

SignalR 允許你把自己的代碼注入 Hub 管道模型,你可以通過繼承 HubPipelineModule 來實現

public class LoggingPipelineModule : HubPipelineModule 
{ 
    protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context) 
    { 
        Debug.WriteLine("=> Invoking " + context.MethodDescriptor.Name + " on hub " + context.MethodDescriptor.Hub.Name); 
        return base.OnBeforeIncoming(context); 
    }   
    protected override bool OnBeforeOutgoing(IHubOutgoingInvokerContext context) 
    { 
        Debug.WriteLine("<= Invoking " + context.Invocation.Method + " on client hub " + context.Invocation.Hub); 
        return base.OnBeforeOutgoing(context); 
    } 
}

然后在 Startup.cs 里注入自定義的 Hub 管道模型

public void Configuration(IAppBuilder app) 
{ 
    GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule()); 
    app.MapSignalR();
}

 

參考鏈接:

https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM