带有signalR < - >静态套接字的asp.net核心

问题描述 投票:0回答:1

使用案例:我有一个带有signalR核心的asp.net核心Web应用程序,用于消息传递。 :)

问题:我必须从套接字连接[通过System.Net.Sockets](具有自己的套接字通信的机器)接收消息

有没有办法将套接字客户端集成到Web应用程序中(主要是Program.cs和Startup.cs?)我如何才能访问signalR以将收到的消息转发到signalR Hub?

谢谢

sockets static signalr .net-core asp.net-core-2.0
1个回答
2
投票

我建议你阅读一下stockticker样本: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;
        }
    }
}

}

在启动时,我创建了这个时钟的单例实例,只要应用程序正在运行,它就会存在。

  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 Call SignalR Core Hub method from Controller中注入hubcontext

© www.soinside.com 2019 - 2024. All rights reserved.