【发布时间】:2020-02-12 07:24:45
【问题描述】:
我在控制台应用程序中使用 Owin 和 SignalR.SelfHost 自托管 SignalR 服务器,也有(.Net 控制台项目)客户端(使用 SignalR.Client NuGet 包),托管服务器后,我可以从客户端,我可以在 OnConnected 方法的 Hub 中看到客户端和 HubCallerContext.ConnectionId 相同的连接 ID。但是当我尝试使用'GlobalHost.ConnectionManager.GetHubContext'和'Context.Clients.All.InvokeAsync(“ReceiveMessage”)'在客户端上调用'ReceiveMessage'方法时,它不会到达客户端(也不例外)。我现在想建立这种连接一种方式,即从服务器到客户端(仅从服务器推送通知)。服务器和客户端都在 .net 框架中(不是 .Net Core)。我在 Global HubContext 上看到的连接 ID 与客户端连接 ID 不同。
1) 服务器端代码,
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public static MonitoringContext _monitoringContext;
static void Main(string[] args)
{
// Start OWIN host
using (WebApp.Start<Startup>("http://localhost:49632/"))
{
Console.WriteLine("Server running on {0}", "http://localhost:49632/");
_monitoringContext = new MonitoringContext();
RunLoop();
//SetTimer();
Console.ReadLine();
}
}
private static void RunLoop()
{
do
{
Thread.Sleep(5000);
_monitoringContext.CallHubClients();
} while (true);
}
public class MonitoringContext
{
IHubContext _hubContext;
public MonitoringContext()
{
_hubContext = GlobalHost.ConnectionManager.GetHubContext<MonitoringHub>();
}
public void CallHubClients()
{
Console.WriteLine("Calling client with ID....");
_hubContext.Clients.All.InvokeAsync("ReceiveMessage");
}
}
[HubName("MonitoringHub")]
public class MonitoringHub : Hub
{
public override Task OnConnected()
{
Console.WriteLine("Client connected...." + this.Context.ConnectionId);
return base.OnConnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Console.WriteLine("Client disconnected....");
return base.OnDisconnected(stopCalled);
}
}
2) 客户端代码-
static HubConnection connection;
static IHubProxy _hubProxy;
static Action OnReceivedAction;
public async void RegisterClient()
{
OnReceivedAction = ReceiveMessage;
connection = new HubConnection("http://localhost:49632/");
_hubProxy = connection.CreateHubProxy("MonitoringHub");
_hubProxy.On("ReceiveMessage", OnReceivedAction);
await connection.Start();
Console.WriteLine("Hub connection started with ID...." + connection.ConnectionId );
}
public void ReceiveMessage()
{
Console.WriteLine("Message Received....Hurrey!!");
}
【问题讨论】:
标签: signalr-hub signalr.client