为什么信号器不能一直稳定?



我正在使用.Net框架4.6的信号器项目。我有一个基本控制器:

public abstract class Base<THub> : ApiController where THub : IHub
{
private static readonly Func<IHubContext> ValueFactory = () => GlobalHost.ConnectionManager.GetHubContext<THub>();
private readonly Lazy<IHubContext> hub = new Lazy<IHubContext>(ValueFactory);
protected IHubContext Hub => hub.Value;
}

所以我正在从 Base 创建我的通知控制器。

public class NewsController : Base<NotificationHub>{
public async Task<IHttpActionResult> CreateNews(string name){
// connect database
// create news on database
....
Hub.Clients.All.send(name);     
}
}

我正在从我的桌面应用程序连接这个集线器。我正在使用创建新闻(字符串名称(操作创建新闻,此操作在最初几次尝试时发送通知。 然后它不会发送几次尝试,有时稍后再次向客户端发送通知。

[HubName("notification")]
public class NotificationHub: Hub
{
private static readonly ConnectionMapping<string> Connections = new ConnectionMapping<string>();
public override Task OnConnected()
{
var name = Context.User.Identity.Name;
Connections.Add(name, Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
var name = Context.User.Identity.Name;
Connections.Remove(name, Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
var name = Context.User.Identity.Name;
if (!Connections.GetConnections(name).Contains(Context.ConnectionId))
{
Connections.Add(name, Context.ConnectionId);
}
return base.OnReconnected();
}
}

我在桌面客户端中设置了断点,没有错误或连接失败。它总是有效。但是通知不会一直发送称为创建新闻(字符串名称(操作的时间。

可能的原因是什么?

每当桌面应用程序启动时,都需要在中心类对象中添加该连接 ID。 因此,还需要在桌面应用中实现 SignalR 对象。

因此,现在当您从桌面应用程序创建新闻时,它将直接调用中心类,您将在其中获取所有活动连接,以及您要在其中发送通知。

所以你需要实现信号R两端。

最新更新