Created
March 1, 2024 03:09
-
-
Save jasper-lai/496f93f27f76e6b5e3f4004323a52f40 to your computer and use it in GitHub Desktop.
SignalR IHubContext<THub, T> 的使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// IHubContext<THub, T> 的使用. | |
// javascript | |
connection.on("ReceiveMessage", function (user, message) { | |
var li = document.createElement("li"); | |
document.getElementById("messagesList").appendChild(li); | |
li.textContent = `${user} says ${message}`; | |
}); | |
// C# 建立一個與 client 的合約, 作為強型別使用. | |
public interface IChatClient | |
{ | |
Task ReceiveMessage(string user, string message); | |
} | |
// C# 建立一個實作 Hub<ChatClient> 的 ChatHub class | |
public class ChatHub : Hub<IChatClient> | |
{ | |
public async Task SendMessage(string user, string message) | |
{ | |
await Clients.All.ReceiveMessage(user, message); | |
} | |
} | |
// C# 某個 service, 在需要時, 會呼叫 client 的方法, 去傳訊息. | |
// 這裡就可以看到 IHubContext 的用法. (它注入了 NotificationService ) | |
public class NotificationService | |
{ | |
private readonly IHubContext<ChatHub, IChatClient> _hubContext; | |
public NotificationService(IHubContext<ChatHub, IChatClient> hubContext) | |
{ | |
_hubContext = hubContext; | |
} | |
public async Task NotifyAll(string message) | |
{ | |
await _hubContext.Clients.All.ReceiveMessage("Server", message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IHubContext<ChatHub, IChatClient>
第1個參數: THub 是 C# 打包的 server side Hub 通訊中樞.
第2個參數: T 是一個將 client callback 打包的一個 C# 介面實作.
例如: server 端要推播訊息給全部的 client, 就可以呼叫 await _hubContext.Clients.All.ReceiveMessage("Server", message);, 它會進入 client 端 javascript 在 connection.on(...) 註冊的 ReceiveMessage callback