首先,您应该通过nuget在服务器应用程序上安装SignalR.Host.Self,在客户端应用程序上安装SignalR.Client:
PM>安装包SignalR.Hosting.Self-版本0.5.2
PM>安装包Microsoft.AspNet.SignalR.Client
然后将以下代码添加到您的项目中;)
(以管理员身份运行项目)
服务器控制台应用程序:
using System;using SignalR.Hubs;namespace SignalR.Hosting.Self.Samples { class Program { static void Main(string[] args) { string url = "http://127.0.0.1:8088/"; var server = new Server(url); // Map the default hub url (/signalr) server.MapHubs(); // Start the server server.Start(); Console.WriteLine("Server running on {0}", url); // Keep going until somebody hits 'x' while (true) { ConsoleKeyInfo ki = Console.ReadKey(true); if (ki.Key == ConsoleKey.X) { break; } } } [HubName("CustomHub")] public class MyHub : Hub { public string Send(string message) { return message; } public void DoSomething(string param) { Clients.addMessage(param); } } }}客户端控制台应用程序:
using System;using SignalR.Client.Hubs;namespace SignalRConsoleApp { internal class Program { private static void Main(string[] args) { //Set connection var connection = new HubConnection("http://127.0.0.1:8088/"); //Make proxy to hub based on hub name on server var myHub = connection.CreateHubProxy("CustomHub"); //Start connection connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetbaseException()); } else { Console.WriteLine("Connected"); } }).Wait(); myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error calling send: {0}", task.Exception.GetbaseException()); } else { Console.WriteLine(task.Result); } }); myHub.On<string>("addMessage", param => { Console.WriteLine(param); }); myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait(); Console.Read(); connection.Stop(); } }}


