SignalR客户端触发事件

时间:2017-02-10 19:20:44

标签: c# signalr signalr-hub signalr.client

我正在尝试像C#(性能原因)那样复制客户端浏览器之类的行为。我想要实现的目标是,对于收到的每个新事件,我的程序应该触发服务器端(Hub),然后通知客户端。有一种方法可以将它作为触发器/检测器处理,以便一旦检测到消息然后执行Hub方法,而不是每次都有重复命中hub方法的while循环。希望这是有道理的

以下客户端代码快照:

IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("PersonHub");
connection.Start().Wait();

//client side method
_hub.On("checkedIn", x => Console.WriteLine(x));

Console.WriteLine("Enter Person Name");
var answer = Console.ReadLine();
while (true) // Better way doing this? trigger or detect new message?
{
    //server side method
    _hub.Invoke("GetByName", answer).Wait();
}

以下Hub代码快照:

[HubName("PersonHub")]
public class PersonHub: Hub
{
    public Person GetByName(string name)
    {
        //logic and etc ...

        Clients.All.checkedIn(name);
    }
}

通过将while循环设置为true,这意味着它将始终调用我不想要的服务器端方法(Hub方法)。如果触发了新事件,则应该使用hub方法。有没有办法以某种方式监听新消息,但如果没有检测到消息则不执行?

1 个答案:

答案 0 :(得分:0)

可能的解决方案是:

    string line;
    while ((line = Console.ReadLine()) != "exit")
    {
         _hub.Invoke("GetByName", line).Wait();
    }
相关问题