SignalR 外部调用自定义Hub类的方法,Clients为null
这是因为外部调用的类的对象和你连接的Hub类的对象,这两个对象 不!一!样!
解决方法
在自定义的Hub类中,注入IHubContext对象,然后在方法中调用IHubContext对象来向前端推送数据
public class DataHub : AbpCommonHub, ITransientDependency
{
public IOnlineClientManager onlineClientManager { get; set; }
public IOnlineClientInfoProvider clientInfoProvider { get; set; }
private IHubContext<DataHub> dataHub { get; } // 就是这个东西!!!!!!!
public DataHub(IOnlineClientManager onlineClientManager, IOnlineClientInfoProvider clientInfoProvider, IHubContext<DataHub> dataHub) // 前两个是继承 AbpCommonHub 来的,可以直接继承AbpHubBase,就没它俩了,最后一个需要
: base(onlineClientManager, clientInfoProvider)
{
this.onlineClientManager = onlineClientManager;
this.clientInfoProvider = clientInfoProvider;
this.dataHub = dataHub; // !!
}
public async Task SendData()
{
await dataHub.Clients.All.SendAsync("sendTracks", GlobalInstance.data);
}
public async Task SendHistoricalData()
{
await dataHub.Clients.All.SendAsync("sendHistoricalTrack", GlobalInstance.dataHis);
}
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await base.OnDisconnectedAsync(exception);
}
}