我建议您阅读股票报价单示例:https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr
我在这里向您展示了一个小示例,您可以根据自己的应用进行调整。您必须从自己的套接字通信中订阅消息,然后才能将此消息转发给连接的客户端。
这是一个如何将时间从服务器发送到客户端的小示例。
(对您来说有趣的部分是 GlobalHost.ConnectionManager.GetHubContext<ClockHub>().Clients.All.sendTime(DateTime.UtcNow.ToString()); 行。您可以将其发送给所有连接的客户端。
我的主类是一个时钟,它向所有连接的客户端发送实际时间:
public class Clock
{
private static Clock _instance;
private Timer timer;
private Clock()
{
timer = new Timer(200);
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{ // ---> This is the important part for you: Get hubContext where ever you use it and call method on hub GlobalHost.ConnectionManager.GetHubContext<ClockHub>().Clients.All.sendTime(DateTime.UtcNow.ToString());
GlobalHost.ConnectionManager.GetHubContext<ClockHub>().Clients.Clients()
}
public static Clock Instance
{
get
{
if (_instance == null)
{
_instance = new Clock();
}
return _instance;
}
}
}
}
在启动时,我创建了这个时钟的一个 sigleton 实例,只要应用程序运行,它就会一直存在。
public class Startup
{
public void Configuration(IAppBuilder app)
{
var inst = Clock.Instance;
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
}
我的中心:
public class ClockHub : Hub<IClockHub>
{
}
Hub接口,定义了服务器可以调用的方法:
public interface IClockHub
{
void sendTime(string actualTime);
}
这是客户端部分:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="timeLabel" ></div>
<script src="scripts/jquery-1.6.4.min.js"></script>
<script src="scripts/jquery.signalR-2.2.0.js"></script>
<script src="signalr/hubs"></script>
<script>
$(function () { // I use jQuery in this example
var ticker = $.connection.clockHub;
function init() {
}
ticker.client.sendTime = function (h) {
$("#timeLabel").html(h);
}
$.connection.hub.start().done(init);
});
</script>
</body>
</html>
如何在 asp.net core 2.x 中注入 hubcontext
Call SignalR Core Hub method from Controller