Example for SignalR 2.2.1 (May 2017)
Server
Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1
[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
class Program
{
static IDisposable SignalR;
static void Main(string[] args)
{
string url = "http://127.0.0.1:8088";
SignalR = WebApp.Start(url);
Console.ReadKey();
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
/* CAMEL CASE & JSON DATE FORMATTING
use SignalRContractResolver from
https://stackoverflow.com/questions/30005575/signalr-use-camel-case
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
*/
app.MapSignalR();
}
}
[HubName("MyHub")]
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
}
Client
(almost the same as Mehrdad Bahrainy reply)
Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1
namespace ConsoleApplication116_SignalRClient
{
class Program
{
private static void Main(string[] args)
{
var connection = new HubConnection("http://127.0.0.1:8088/");
var myHub = connection.CreateHubProxy("MyHub");
Console.WriteLine("Enter your name");
string name = Console.ReadLine();
connection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
myHub.On<string, string>("addMessage", (s1, s2) => {
Console.WriteLine(s1 + ": " + s2);
});
while (true)
{
Console.WriteLine("Please Enter Message");
string message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
break;
}
myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
if (task1.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
}
else
{
Console.WriteLine(task1.Result);
}
});
}
}
}).Wait();
Console.Read();
connection.Stop();
}
}
}