SignalR客户端触发事件
问题描述:
我想复制像客户端浏览器,但在C#(性能原因)的行为。我试图实现的是,对于接收到的每个新事件,我的程序都应该触发服务器端(Hub),然后通知客户端。而不是有一个while循环,即使没有消息,每次都会反复使用hub方法,是否有办法将其视为触发器/检测,以便一旦检测到消息,然后执行Hub方法?希望这是有道理SignalR客户端触发事件
下面的客户端代码快照:
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();
}
下面枢纽代码快照:
[HubName("PersonHub")]
public class PersonHub: Hub
{
public Person GetByName(string name)
{
//logic and etc ...
Clients.All.checkedIn(name);
}
}
通过while循环设置为true,这意味着,这将始终调用服务器我不想要的方法(Hub方法)。如果这些新事件触发了,那么它应该碰到集线器方法。有没有办法以某种方式监听新消息,但是如果没有检测到消息则不执行?
答
一种可能的解决方案是:
string line;
while ((line = Console.ReadLine()) != "exit")
{
_hub.Invoke("GetByName", line).Wait();
}