Is there any way to stop SignalR server? I have self-hosted SignalR server as Windows service but i can't find any way to stop server/service.
I tried this but it doesn't work - server keeps listening and prevents service from stopping.
Alternatively, how can i stop service altogether, forcing SignalR shutdown?
[edit]:
Most of source i cannot share (copyright/security) but I'll do my best:
SignalR server init
Task signalRTask = null;
IDisposable SignalR;
#region SignalR server init
// Kreiraj SignalR server
try
{
cancelTokenSrc = new CancellationTokenSource();
signalRTask = Task.Factory.StartNew(RunSignalR, TaskCreationOptions.LongRunning, cancelTokenSrc.Token);
logfile.Info("Starting notifications pool thread...");
//Console.WriteLine(DateTime.Now.ToString("dd.MM.yyyy. HH:mm:ss ") + "Starting notifications pool thread...");
senderThread = new Thread(delegate()
{
sender.poolEvents();
});
senderThread.Start();
}
catch (Exception ex)
{
// greška u startanju SignalR servera
ServiceEngine.logfile.Info("Error starting SignalR on " + signalr_bind + " with error:" + ex.ToString());
//Console.WriteLine(DateTime.Now.ToString("dd.MM.yyyy. HH:mm:ss ") + "Error starting SignalR # {1} with error {0}", ex.ToString(), signalr_bind);
}
#endregion
#region SignalR start
// pokreće signalR server
public void RunSignalR(object task)
{
try
{
logfile.Info("Starting SignalR server on " + signalRBindAddr);
SignalR = WebApp.Start(signalRBindAddr);
logfile.Info("SignalR server running on " + signalRBindAddr);
}
catch (Exception ex)
{
ServiceEngine.logfile.Info("Error starting SignalR: " + ex.ToString());
}
//Console.WriteLine(DateTime.Now.ToString("dd.MM.yyyy. HH:mm:ss ") + "SignalR server running on {0}", signalRBindAddr);
}
#endregion
public class Startup
{
public void Configuration(IAppBuilder app)
{
var hubConfiguration = new HubConfiguration { };
hubConfiguration.EnableDetailedErrors = true;
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(hubConfiguration);
}
}
public void Stop()
{
try
{
logfile.Info("Stop called...");
SignalR.Dispose();
cancelTokenSrc.Cancel();
//signalRTask.Dispose();
logfile.Info("SignalR down, exit...");
//Console.WriteLine(DateTime.Now.ToString("dd.MM.yyyy. HH:mm:ss ") + "SignalR down, exit...");
}
catch (Exception ex)
{
ServiceEngine.logfile.Info(ex.ToString());
}
}
When i call Stop(), SignalR keeps listening (clients can connect, port has status "LISTEN"...) and i can't stop service.
P.S. Sorry for bad formatting and bad English
Not clearly a complete answer, but I managed to achieve a pause, not a stop in my ancient services as explained in Self-Hosting SignalR in a Windows Service.
However, I then refactored all of them to be micro services, placing the hubs which must be stopped in separate micro services. This solution allows you to manually start and stop the services via SCM or via direct invocation if you are running on a container.
Architecturally speaking, the latter solution has a certain overhead as you are adding a new layer which requires authentication, federation and data IO. Depending on the context, you might already have the infrastructure to support that.
Related
I am new to Azure Service Bus and appreciate any help I can get.
In my current project, using c# and Azure.Messaging.ServiceBus we use an On-Premise server running a "Task Engine" windows service that listens to various queues (including MSMQ) to receive and process messages. We are migrating to Azure Service Bus Queue now.
I implemented ReceiveMessageAsync() method to read and process messages. The connection is persistent because the base class of the Task Engine service is already running in loop. While the below code works fine from my local pc (connected to VPN), it fails with the following error as soon as it's deployed to the on-premise server. The server also uses up all memory and shuts down causing other queues to terminate.
Error messages:
Azure.Messaging.ServiceBus.ServiceBusException: Creation of ReceivingAmqpLink did not complete in 30000 milliseconds. (ServiceTimeout)
Azure.Messaging.ServiceBus.ServiceBusException: 'receiver31' is closed (GeneralError)
Note:
Private Endpoint is enabled on Azure Service Bus and we use token and client credentials to connect to Azure.
All code below works fine locally when run for more than 2 hours and processes messages as soon as they are manually sent to queue using Azure Portal.
Code:
public **override **void StartUp(ContextBase context)
{
// Save the thread context
base.StartUp(context);
//Get values from Config
_tenantId = System.Configuration.ConfigurationManager.AppSettings["tenant-id"];
_clientId = System.Configuration.ConfigurationManager.AppSettings["client-id"];
_clientSecret = System.Configuration.ConfigurationManager.AppSettings["client-secret"];
_servicebusNamespace = System.Configuration.ConfigurationManager.AppSettings["servicebus-namespace"];
_messageQueueName = System.Configuration.ConfigurationManager.AppSettings["servicebus-inbound-queue"];
getAzureServiceBusAccess();
// Set the running flag
_isRunning = true;
}
//Called when service is initialized and then when Reset Connection happens due to error
private static void getAzureServiceBusAccess()
{
var _token = new ClientSecretCredential(_tenantId, _clientId, _clientSecret);
var clientOptions = new ServiceBusClientOptions()
{
TransportType = ServiceBusTransportType.AmqpWebSockets
};
_serviceBusClient = new ServiceBusClient(_servicebusNamespace, _token, clientOptions);
_serviceBusReceiver = _serviceBusClient.CreateReceiver(_messageQueueName, new ServiceBusReceiverOptions());
}
public **override **void DoAction()
{
// Make sure we haven't shut down
if (_isRunning)
{
// Wait next message
tryReceiveMessages();
}
}
private async void tryReceiveMessages()
{
try
{
ServiceBusReceivedMessage message = null;
message = await _serviceBusReceiver.ReceiveMessageAsync();
if (message != null && _isRunning)
{
try
{
string _messageBody = message.Body.ToString();
// <<Send message body to Task Adapter that adds it to the database and processes the job>>
await _serviceBusReceiver.CompleteMessageAsync(message);
}
catch (ServiceBusException s)
{
Tracer.RaiseError(Source.AzureSB, "Azure Service Bus Queue resulted in exception when processing message.", s);
throw;
}
catch (Exception ex)
{
Tracer.RaiseError(Source.AzureSB, "Unexpected error occurred moving task from Azure Service Bus to database; attempting to re-queue message.", ex);
if (message != null)
await _serviceBusReceiver.AbandonMessageAsync(message);
}
}
}
catch (ServiceBusException s)
{
tryResetConnections(s);
}
catch(Exception ex)
{
Tracer.RaiseError(Source.AzureSB, "Azure Service Bus Queue reset connection error.", ex);
throw;
}
}
private void tryResetConnections(Exception exception)
{
try
{
if (DateTime.Now.Subtract(LastQueueReset).TotalSeconds > 1800)
{
LastQueueReset = DateTime.Now;
getAzureServiceBusAccess();
}
else
{
//Send notification email to dev group
}
}
catch (Exception ex)
{
throw;
}
}
private async void closeAndDisposeConnectionAsync()
{
try
{
await _serviceBusReceiver.DisposeAsync();
}
catch(Exception ex)
{
//Do not throw and eat exception - Receiver may have been already disposed
}
try
{
await _serviceBusClient.DisposeAsync();
}
catch (Exception ex)
{
//Do not throw and eat exception - Client may have been already disposed
}
}
We tried to open the network settings on Azure Service Bus to public but that didn't resolve the issue.
I have requested the DevOps team to open ports 443, 5671 and 5672 for AMQPWebSockets and still waiting to hear back to test.
I'm using
WebApp.Start<Startup>(url)
to host Signalr hub in windows service. For some reason my hub doesn't accept connection after 2-3 day of running, How i can detect it's unresponsiveness and restart it?
First of all, you should find a reason why your Windows Service crashes. Write logs for events, use try catch block and write every error to eventlog.
What about control your Windows Service: have a look ServiceController class
Add such like a method:
public void StartService()
{
using (ServiceController service = new ServiceController(serviceName))
{
try
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running);
}
catch (Exception ex)
{
throw new Exception($"Can not Start the Windows Service [{serviceName}]", ex);
}
}
}
public void StartOrRestart()
{
if (IsRunningStatus)
RestartService();
else if (IsStoppedStatus)
StartService();
}
UPDATE:
If you have problems only with Hub then try to start it from clients such:
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.you can set the time based your requirement
});
Feel free to add comments with more information from you issue
I have SignalR server as Class Library Project and i referenced it in Console application (to simulate Windows service)
Here is code for SignalR
public void Start()
{
try
{
string url = #"http://*:8081";
using (WebApp.Start<Startup>(url))
{
Logger.Info(string.Format("Server running at {0}", url));
}
}
catch (Exception ex)
{
Logger.Exception(ex, "Signalr start");
}
Run = true;
Logger.Info("Starting Worker");
workerThread = new Thread(() =>
{
Worker();
});
workerThread.Start();
}
And here is Startup class
public class Startup
{
Microsoft.AspNet.SignalR.HubConfiguration hubconfiguration = null;
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
hubconfiguration = new HubConfiguration();
hubconfiguration.EnableDetailedErrors = true;
app.MapSignalR(hubconfiguration);
}
}
So, it is in one thread, and worker is in another. That seems fine since i did it in other project where it works. Worker thread isn't problem, it's just empty loop, not related to server in any way.
Problem is that server seems to "stop" - when i look with Netstat, nobody is listening on port 8081. There is no exception, it just silently fails.
I referenced Owin.Cors (and Owin.Host.HttpListener) in console project that actually runs this server but as I said, server just stops.
When I try to connect, client says "connection actively refused" and Putty (telnet) also says "can't connect".
Where is the problem? In a nutshell, i have Class Library with SignalR server that is referenced in Console project that runs it but server just wont work.
[edit]
And there is code of Console app that starts service
static void Main(string[] args)
{
ServiceEngine Engine = new ServiceEngine();
Engine.Start();
Console.ReadKey();
Engine.Stop();
}
P.S. Sorry for my bad English.
Well, i solved it. Here was a problem:
public static void Start()
{
try
{
string url = #"http://127.0.0.1:8081";
WebApp.Start<Startup>(url);
Logger.Info(string.Format("Server running at {0}", url));
}
catch (Exception ex)
{
Logger.Exception(ex, "signalr start");
}
Run = true;
Logger.Info("Starting Worker");
workerThread = new Thread(() =>
{
Worker();
});
workerThread.Start();
}
As you can see, using statement was removed and now it works fine! Interesting note - you can also make Singleton implementation of this "Engine", and it will also work.
I got Solution after doing lot of R & D. And Its a Simple change related to Account and Access Rights.
Use LocalSystem Account instead of LocalService Account in Service Installer.
You can do this either from doing below change in design view of your service installer:
Properties of Service Process Installer -> Set Account to LocalSystem.
or by doing below change in in designer.cs file of your service installer:
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
Signalr is usually used in "server" side asp.net through hubs and connections. What I'm trying to accomplish (if possible) is using signalr as a "client" in a website.
I have 2 websites, one as a server and another as a client.
I tried this
public void Start()
{
new Task(this.Listen).Start();
//new Thread(this.Listen).Start();
}
private async void Listen()
{
try
{
using (var hubConnection = new HubConnection("http://localhost:8081"))
{
var myHub = hubConnection.CreateHubProxy("mediaHub");
hubConnection.StateChanged += change => System.Diagnostics.Debug.WriteLine(change.OldState + " => " + change.NewState);
myHub.On<string>(
"log",
message =>
System.Diagnostics.Debug.WriteLine(message + " Notified !"));
await hubConnection.Start();
}
}
catch (Exception exc)
{
// ...
}
}
The server is calling the client like this:
var hub = GlobalHost.ConnectionManager.GetHubContext<MediaHub>() ;
hub.Clients.All.log("Server: " + message);
Nothing reaches the client !
As soon as your connection is ready, you actually dispose it, so it does not stay around. As a quick test, remove the using stuff and make your hubConnection a static member of your class, and check if you get called. If you do, then from there you can refine it, but at least you have clearer what's going on.
I have a WCF windows service which exposes an API to a windows form application.
API connection to client:
var serviceType = typeof(Mail2SmsServerApi);
var uri = new Uri("http://localhost:8000/");
host = new ServiceHost(serviceType, new[] { uri });
var behaviour = new ServiceMetadataBehavior() { HttpGetEnabled = true };
host.Description.Behaviors.Add(behaviour);
host.AddServiceEndpoint(serviceType, new BasicHttpBinding(), "Hello");
host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "mex");
host.Open();
My ServiceContract:
[ServiceContract]
public class Mail2SmsServerApi
{
[OperationContract]
public string Imei()
{
try
{
GSMHandler gsm = new GSMHandler();
return gsm.GetImei();
}
catch (Exception ex)
{
LogText.Error("API GetImei(), exception: " + ex.ToString());
return null;
}
}
}
My GSMHandler class and method:
public bool OpenConnection()
{
modem = new GsmPhone(_comport, _baudrate, _timeout);
if (!comm.IsConnected())
{
try
{
modem.Open();
return true;
}
catch (Exception ex)
{
LogText.Debug("OpenConnection(), exception" + ex.ToString());
return false;
}
}
else
{
try
{
modem.Close();
modem.Open();
return true;
}
catch (Exception ex)
{
LogText.Debug("OpenConnection(), exception" + ex.ToString());
return false;
}
}
}
public string GetImei()
{
string imei = "";
try
{
imei = modem.RequestSerialNumber();
LogText.Debug("IMEI:" + _IMEI);
return imei;
}
catch (Exception ex)
{
LogText.Error("Error caught in GetImei(), exception: " + ex.ToString());
return imei;
}
}
When the OnStart method in my service are called, I'm opening a connection to the modem with :
gsm = new GSMHandler();
gsm.OpenConnection();
When OnStop are called, I'm stopping it with:
gsm = new GSMHandler();
gsm.OpenConnection();
My idea was that, with this design the service would handle the communication and the client and service could interact with the modem without getting a com port not open or com port busy problem. This is obviously wrong, since I'm not able to return values from the modem this way. It has to be a design failure from my side.
What I'm trying to achieve is that a client can talk to the modem through the service, and that not both of them make a direct connection to the modem. But that the service can handle the opening and closing of connection to modem, and pass commands in to the modem from the client...
So my question is, what's the appropriate way to design such a scenario? I'm not asking for the code, just how It's usual to design it...
I'm appreciating all answers :) Thanks in advance!
I think you might have much more success if you performed the interaction with the modem as a single unit of work.
For example, design your service such that the caller calls a single method to send a text message, providing all of the necessary detail in the interface call.
The service method then performs all of the tasks necessary to open the modem, send the text message, and close the modem, in a single unit of work.
This design will allow you to ensure that the modem is always opened and closed correctly and completely within the unit of work instead of waiting for additional commands through the service that may never arrive.
Also, this design will allow you to eventually correctly support multiple modems, which your current design will not. You could have a modem pool and when a new request arrives, you could obtain an available modem from the pool, perform the unit of work, then return the modem to the pool on completion, even in a failure situation.