SignalR 2.0 .NET控制台客户端

时间:2014-03-03 08:00:45

标签: c# asp.net .net signalr signalr.client

我有我的服务器控制台应用程序:

    static void Main(string[] args)
    {
        string url = "http://localhost:8080";
        using (WebApp.Start(url))
        {
            MyHub hub = new MyHub();
            Console.WriteLine("Server running on {0}", url);
            var key = Console.ReadLine();
            while (key != "quit")
            {
                hub.Send("Server", key);
            }
        }
    }

public class MyHub : Hub
{
    public void Send(string name, string message)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        context.Clients.All.addMessage(name, message);
    }
}
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}

我的.NET客户端应用

    static void Main(string[] args)
    {

        MainAsync().Wait();
        Console.ReadLine();
    }

    static async Task MainAsync()
    {
        try
        {

            var hubConnection = new HubConnection("http://localhost:8080/");
            //hubConnection.TraceLevel = TraceLevels.All;
            //hubConnection.TraceWriter = Console.Out;
            IHubProxy hubProxy = hubConnection.CreateHubProxy("MyHub");
            hubProxy.On("addMessage", data =>
                {
                    Console.WriteLine("Incoming data: {0} {1}", data.name, data.message);
                });
            ServicePointManager.DefaultConnectionLimit = 10;
            await hubConnection.Start();

        }
        catch (Exception ex)
        {

        }
    }

运行客户端时没有任何错误。但是,控制台上没有任何内容打印出来。

当我取消注释这两行时:

hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;

我能在控制台中看到一些跟踪输出

07:56:28.0121460 - 355ca933-de49-400b-b859-c9dde6361151 - WS: OnMessage({"C":"d-
69A14839-B,0|C,0|D,1|E,0","S":1,"M":[]})
07:56:28.0277722 - 355ca933-de49-400b-b859-c9dde6361151 - ChangeState(Connecting
, Connected)
07:56:33.4655493 - 355ca933-de49-400b-b859-c9dde6361151 - WS: OnMessage({"C":"d-
69A14839-B,1|C,0|D,1|E,0","M":[{"H":"MyHub","M":"addMessage","A":["Server","Hello World"]}]}
)
07:56:37.9657773 - 355ca933-de49-400b-b859-c9dde6361151 - WS: OnMessage({})
 07:56:47.9975354 - 355ca933-de49-400b-b859-c9dde6361151 - WS: OnMessage({})

“服务器”和“Hello World”是从服务器发送的消息,所以我猜客户端正在接收消息,只是因为我可能以错误的方式将它们打印到控制台

有人可以帮忙吗?

其他信息:我能够在我的MVC应用程序上收到很好的消息。

1 个答案:

答案 0 :(得分:12)

您不应该将hubProxy事件处理程序声明为此吗?

hubProxy.On<string, string>("Send", (name, message) => 
{
   Console.WriteLine("Incoming data: {0} {1}", name, message);
});