Hub方法只运行一次

时间:2017-12-13 10:07:38

标签: javascript c# asp.net-core asp.net-core-signalr

(我是Signalr的新手)

我正在开发一个使用Signalr-core实时更新页面的Web应用程序。

我走进的问题是,当我运行多个客户端时,我运行的方法会像客户一样多次运行。

所以我想知道是否有办法让第一个客户端调用集线器方法,然后让它继续运行并向所有连接的客户端广播。

这就是我对我的客户所做的事情:

connection.on('update', (id, Color) => {
var x = document.getElementById(id);
if (Color === "green" && x.classList.contains("red"))
{            
    //console.log("green");
    x.classList.remove("red");
    x.classList.add("green");
}            
else if (Color === "red" && x.classList.contains("green"))
{            
    //console.log("Red");
    x.classList.remove("green");
    x.classList.add("red");
}});

connection.start()
.then(() => connection.invoke('updateclient', updating));

这就是我正在用我的中心做的事情:

 public void UpdateClient(bool updating)//this must run only once
    {
        while (updating == true)
        {
            Thread.Sleep(2000);
            foreach (var item in _context.Devices)
            {

                IPHostEntry hostEntry = Dns.GetHostEntry(item.DeviceName);
                IPAddress[] ips = hostEntry.AddressList;
                foreach (IPAddress Ip in ips)
                {
                    Ping MyPing = new Ping();

                    PingReply reply = MyPing.Send(Ip, 500);
                    if (reply.Status == IPStatus.Success)
                    {
                        Color = "green";
                        Clients.All.InvokeAsync("update", item.DeviceID, Color);

                        break;
                    }
                    else
                    {
                        Color = "red";
                        Clients.All.InvokeAsync("update", item.DeviceID, Color);
                    }
                }

            }

        }
    }

如果我不清楚某事,请告诉我。

并提前感谢你。

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,您可以在首次出现任何客户端时调用ModelAdminGroup方法。我提出的选项如下:

为连接到集线器

的客户端使用静态列表是quite common
UpdateClient

在您的集线器中,覆盖OnConnected和OnDisconnected方法以在列表中添加/删除客户端,并为您的目的定义连接到集线器的第一个客户端。

 public static class UserHandler
 {
     public static List<string> UserList = new List<string>();
 }

我没有考虑您的业务逻辑或您的需求,这只是一个普遍的想法。例如,您可能希望在所有客户端都关闭时添加一些逻辑,您应该使用更新标志在public class MyHub : Hub { private static IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); public override Task OnConnected() { //Here check the list if this is going to be our first client and if so call your method, next time because our list is filled your method won't be invoked. if(UserHandler.UserList.Count==0) UpdateClient(true); UserHandler.UserList.Add(Context.ConnectionId) return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { UserHandler.UserList.RemoveAll(u => u.ConnectionId == Context.ConnectionId); return base.OnDisconnected(stopCalled); } } 内停止循环。

相关问题