SignalR Server Console Application

Mert Çağrıberk Erhan
1 min readOct 25, 2018

--

Required Packages
Powershell or Nuget Package Manager
Install-Package Microsoft.AspNet.SignalR.SelfHost
Install-Package Microsoft.Owin.Cors

Program.cs
using Microsoft.Owin.Hosting;
using System;

class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server runing on {0}", url);
Console.ReadLine();
}
}
}
Startup.cs
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.AspNet.SignalR;

[assembly: OwinStartup(typeof(ConsoleApp.Startup))]

public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(CorsOptions.AllowAll);

var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;

app.MapSignalR(hubConfiguration);
}
}
MyHub.cs
using Microsoft.AspNet.SignalR;
using System;
using System.Threading.Tasks;

class MyHub : Hub
{
public override Task OnConnected()
{
string clientConnectionId = Context.ConnectionId;
Console.WriteLine("Client connected with " + clientConnectionId + " connetionId");
return base.OnConnected();
}

public override Task OnDisconnected(bool stopCalled)
{
if (stopCalled)
{
Console.WriteLine(String.Format("Client {0} explicitly closed the connection.", Context.ConnectionId));
}
else
{
Console.WriteLine(String.Format("Client {0} timed out .", Context.ConnectionId));
}
return base.OnDisconnected(stopCalled);
}

public override Task OnReconnected()
{
Console.WriteLine(Context.ConnectionId + " reconnected.");
// Add your own code here.
// For example: in a chat application, you might have marked the
// user as offline after a period of inactivity; in that case
// mark the user as online again.
return base.OnReconnected();
}
}

--

--