我已将Microsoft.AspNetCore.SignalR.Client实现为服务。我可以成功注入它并向集线器发送消息。但我无法弄清楚如何从该特定班级收听集线器(接收消息)。
我可以通过HubClient
操作在OnBroadcast
收到消息。
public class HubClient : IHub
{
private HubConnection hubConnection;
private async Task ConnectAsync()
{
// Connect
hubConnection.On<string>("Broadcast", OnBroadcast);
}
public async Task Send(string message)
{
await hubConnection.SendAsync("method", message);
}
private void OnBroadcast(string message)
{
// Received message
}
}
如何从MyClass
接收和处理消息?如何让OnBroadcast(string message)
在MyClass
中工作,以便我可以对消息做些什么?我有多个类,每个类都必须处理来自集线器的消息。
public class MyClass
{
private readonly IHub hub;
public MyClass(IHub hub)
{
this.hub = hub;
}
public Task Send(string message)
{
// Sending message to the hub works
await hub.Send(message);
}
// How can I process received messages here?
}
答案 0 :(得分:0)
public interface IHub
{
Task Send(string data);
event Action<string> OnBroadcastAction;
}
public class HubClient : IHub
{
private HubConnection hubConnection;
public event Action<string> OnBroadcastAction;
private async Task ConnectAsync()
{
// Connect
hubConnection.On<string>("Broadcast", OnBroadcast);
}
public async Task Send(string message)
{
await hubConnection.SendAsync("method", message);
}
private void OnBroadcast(string message)
{
OnBroadcastAction?.Invoke(message);
}
}
public class MyClass
{
private readonly IHub hub;
public MyClass(IHub hub)
{
this.hub = hub;
hub.OnBroadcastAction += OnBroadcast;
}
public Task Send(string message)
{
await hub.Send(message);
}
private void OnBroadcast(string message)
{
Console.WriteLine(message);
}
}