![](/img/trans.png)
[英]signalR calls a server method and that method calls a callback method ,outside the hub. How can I call client function from that method?
[英]Call Client method outside SignalR Project
我擔心在以下情況下如何使用SgnalR:
有一個非中心服務項目,該項目定期運行耗時的任務。 應將運行任務的進度通知客戶端。 經過研究后,SignalR似乎是實現此目的的正確選擇。
問題是,我希望Service-Hub-Clients系統盡可能寬松地耦合。 因此,我將Hub托管在IIS中,並且正如SignalR文檔建議的那樣,在外部項目中添加了對Hub上下文的引用,並稱為客戶端方法:
hubContext = GlobalHost.ConnectionManager.GetHubContext<TheHub>()
hubContext.Clients.All.progress(n, i);
客戶端:
private void InitHub()
{
hubConnection = new HubConnection(ConfigurationManager.AppSettings["hubConnection"]);
hubProxy = hubConnection.CreateHubProxy("TheHub");
hubConnection.Start().Wait();
}
hubProxy.On<int, int>("progress", (total, done) =>
{
task1Bar.Invoke(t => t.Maximum = total);
task1Bar.Invoke(t => t.Value = done);
});
在客戶端,該方法沒有被調用,經過兩天的研究,我無法使其工作,盡管從集線器本身進行調用時,它仍然可以正常工作。 我懷疑我缺少一些配置
如果調用者將是Web項目以外的任何項目,則不能在Hub類或服務中使用GlobalHost.Connection管理器。
GlobalHost.ConnectionManager.GetHubContext<TheHub>()
相反,您應該創建一個服務類,該服務類將從調用方中提取集線器。 服務類應具有以下內容:
// This method is what the caller sees, and abstracts the communication with the Hub
public void NotifyGroup(string groupName, string message)
{
Execute("NotifyGroup", groupName, message);
}
// This is the method that calls the Hub
private void Execute(string methodName, params object[] parameters)
{
using (var connection = new HubConnection("http://localhost/"))
{
_myHub = connection.CreateHubProxy("TheHub");
connection.Start().Wait();
_myHub.Invoke(methodName, parameters);
connection.Stop();
}
}
最后一點是集線器本身,應類似於:
public void NotifyGroup(string groupName, string message)
{
var group = Clients.Group(groupName);
if (group == null)
{
Log.IfWarn(() => $"Group '{groupName}' is not registered");
return;
}
group.NotifyGroup(message);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.