Signalr .Net Client Console应用程序只接收来自集线器的消息

问题描述:

我在控制台应用程序中使用Signalr .Net Client从Signalr Hub接收消息,这是一个单独的Web应用程序。Signalr .Net Client Console应用程序只接收来自集线器的消息

我的控制台应用程序正在正确连接到集线器,并且只接收来自集线器的消息一次。然后,Signalr .Net客户端中的客户端方法不会被调用。

一旦我停止了控制台应用程序并运行它,它又一次从集线器收到一条消息,但没有任何反应。

这是我基地代码

public override Task OnConnected() 
     { 
      try 
      { 
       var cType = Context.QueryString["type"]; 
       var connectionId = Context.ConnectionId; 
       var connectedUserList = (from d in Users 
             where d.ClientType == cType 
                  select d).ToList(); 
       if (connectedUserList.Count > 0) 
       { 
        var conUser = connectedUserList.First<ConnectedUsers>(); 
        conUser.ConnectionIds.Add(connectionId); 
       } 
       else 
       { 
        var newUser = new ConnectedUsers 
        { 
         ConnectionIds = new HashSet<string> {connectionId} 
         , 
         ClientType = cType 
        }; 
        Users.Add(newUser); 
       } 
      } 
      catch (Exception ex) 
      { 

      ).Error(ex); 
      } 
      return base.OnConnected(); 
     } 

和我的.NET客户端连接

static void Main(string[] args) 
     { 

      SignalrHandler(); 
      Console.ReadLine(); 

     } 

     public static async void SignalrHandler() 
     { 
      var url = ConfigurationSettings.AppSettings["Url"] ?? @"http://localhost:1010/"; 
      var querystringData = new Dictionary<string, string> { { "type", "WIN" } }; 
      _hubConnection = new HubConnection(url, querystringData); 
      MarcolinMainProxy = _hubConnection.CreateHubProxy("MainHub"); 
      MarcolinMainProxy.On<string>("sendAlert", type => InvokeMethod(type));  
      await _hubConnection.Start(); 

     } 

客户方法

private static void InvokeMethod(string type) 
     { 
      Console.WriteLine(String.Format("Recieved Message From Server On :{0}",System.DateTime.Now.ToString())); 
      Console.WriteLine("Message Received"); 

      Console.ReadLine(); 


     } 

而且这发生在我使用Invoke方法与以下行

MarcolinMainProxy.On<string>("sendAlert", type => InvokeMethod(type)); 

当我使用下面的行它的工作原理..

MarcolinMainProxy.On<string>("sendAlert", stock => Console.WriteLine("Symbol {0} Price {1}", "sd", "sdde")); 
+0

认沽调用'SignalrHandler'后的调试消息看看代码的执行是否通过它,也许它不会阻塞并等待新消息,所以代码首次听,并在此之后,应用程序结束 –

+0

@HaithamShaddad我已经更新了这个问题。我认为问题在于客户端调用方法。 – tarzanbappa

+0

所以,它在你保持内联代码的情况下工作,但如果你调用'InvokeMethod'方法则不起作用? –

查看以下链接

https://damienbod.com/2013/11/13/signalr-messaging-a-complete-client-with-a-console-application/

您必须更改您的代码

MarcolinMainProxy.On<string>("sendAlert", InvokeMethod);