Here's my SignalR console app which works fine. It's able to receive messages from the Hub and print them onto the console.
static void Main(string[] args)
{
MainAsync().Wait();
Console.ReadLine();
}
static async Task MainAsync()
{
try
{
var hubConnection = new HubConnection("http://localhost:8080/");
IHubProxy hubProxy = hubConnection.CreateHubProxy("MyHub");
hubProxy.On<string, string>("addMessage", (name, message) =>
{
Console.WriteLine("Incoming data: {0} {1}", name, message);
});
ServicePointManager.DefaultConnectionLimit = 10;
await hubConnection.Start();
}
catch (Exception ex)
{
}
}
I created a windows service, and copied almost character for character, except the part where it prints to the console, I printed it to a log file
protected override void OnStart(string[] args)
{
Log.Info("Starting...");
StartListening().Wait();
}
private static async Task StartListening()
{
try
{
var hubConnection = new HubConnection("http://localhost:8080/");
IHubProxy hubProxy = hubConnection.CreateHubProxy("MyHub");
hubProxy.On<string, string>("addMessage", (name, message) =>
{
Log.Info(string.Format("Incoming data: {0} {1}", name, message));
});
ServicePointManager.DefaultConnectionLimit = 10;
await hubConnection.Start();
Log.Info("Connected");
}
catch (Exception ex)
{
Log.Error(ex);
}
}
Here's my server code:
static void Main(string[] args)
{
//string url = "http://localhost:8080";
string url = "http://*: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 Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
//Clients.All.addMessage(name, message);
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.addMessage(name, message);
}
}
However, nothing gets written to the log file except "Starting..." and "Connected"
There were no exceptions thrown either.
Do I need to include anything else or modify the code for SignalR to work on a windows service?
Update
Apparently, it seemed that changing this line
string url = "http://localhost:8080";
to this
string url = "http://*:8080";
in my server code solved my issue. But I don't know why.
OnStart
code is wrong.OnStart
is called on a thread that doesn't "belong" to you - it's wrong to block it with aWait
call. The Service Control manager doesn't consider your service to be started until you return fromOnStart
. If you want to have something running (or blocking) on a thread, you need to create one for yourself.