My WPF app is running locally using SignalR .Net Client to connect to the SignalR hub with async code.
I would like to solve the case that the SignalR hub goes down and the WPF app automatically reconnects when the SignalR hub comes back online after for example 10 minutes. I would like to register an async action to the HubConnection closed event. The automated SignalR reconnect logic is awesome but when that timeout is exceeded it should still reconnect to the hub. The example is using Polly to retry until success after the connection was closed.
The issue with following code is that there is no control over the async action (HubConnectionClosedEventHandler) and when closing the WPF app it doesn't properly dispose those running tasks. There is also the strange behavior that Log4Net stops logging after a few retries. What is the best practice for registering an async action to the closed event to try to reconnect ? What am I doing wrong ?
private async Task InitializeAsync()
{
this.hubConnection.Closed += this.HubConnectionClosedEventHandler();
}
private Action HubConnectionClosedEventHandler()
{
return () => this.HubConnectionClosed().Wait();
}
private async Task HubConnectionClosed()
{
App.LogDebug("Connection closed event triggered.");
await this.StartSignalRConnection();
}
private async Task StartSignalRConnection()
{
App.LogDebug("Initialize policy.");
var policy = Policy.Handle<Exception>().WaitAndRetryForeverAsync(retryAttempt => TimeSpan.FromSeconds(2));
await policy.ExecuteAsync(this.StartSignalRConnectionAsync);
}
private async Task StartSignalRConnectionAsync()
{
App.LogDebug("Start connection.");
await this.hubConnection.Start()
.ContinueWith(
task =>
{
if (task.Exception != null || task.IsFaulted)
{
var exceptionMessage =
$"There was an error opening the connection with connection '{CustomSettings.CallcenterHubConnection}'";
App.LogError(exceptionMessage,
task.Exception);
throw new InvalidOperationException(exceptionMessage);
}
App.LogDebug(
$"Connected successfully with connection '{CustomSettings.CallcenterHubConnection}'");
});
}
public void Stop()
{
try
{
this.hubConnection.Closed -= this.HubConnectionClosedEventHandler();
if (this.hubConnection.State != ConnectionState.Disconnected) this.hubConnection.Stop();
}
catch (Exception ex)
{
App.LogError("Exception when stopping", ex);
}
}
It seems that hijacking the closed event for a reconnect is just wrong. In the end we ended up changing the disconnect timeout to 5 minutes and visualizing the WPF tool with a disconnect icon. If the server had some serious issue and is fixed then the user manually must restart the WPF tool.
Related
I'm currently working on a System.Net.WebSockets implementation that will be using cellular networks to send data packets about the device in a real-time manner. Using cellular network means that my solution should be able to reconnect a socket when the network occasionally loses connection. The only way that I have been able to do this is by creating a new instance of the ClientWebSocket and then sending the connect message asynchronously.
This is not my exact code but hopefully it will get the idea across of what I am trying to do.
void PublisherConnect()
{
myWebSocket = new ClientWebSocket();
Task.Run(async () =>
{
if (myWebSocket.ConnectionState != WebSocketState.Open)
{
try
{
await myWebSocket.ConnectAsync(HostString);
}
catch (WebSocketException ee)
{
Debug.WriteLine(ee.Message);
}
}
}
}
internal async Task ConnectAsync(Uri uri)
{
using (var cts = new CancellationTokenSource())
{
try
{
await myWebSocket.ConnectAsync(uri, CancellationToken.None);
manualState = false;
}
catch (Exception)
{
throw;
}
}
}
If I try to connect again with the same object after a clean disconnect, an error is thrown with the message, "The websocket has already been started." What is it about WebSockets that I don't understand?
EDIT - I am building this into a NuGet package to be used as a library for other apps so I need to stay around .NET 4.6 due to how the programs that will be consuming this function.
I wrote a Client/Server async classes which works fine in the console. I created a WinForm project for the server which subscribes to an event thrown by the server when there is a .Pending() connection and writes some messages into a textbox - which causes a Cross-Thread exception. The exception does not surprise me, however I am looking for a way to invoke that event without causing this exception, without handling it on the GUI/Control with .InvokeRequired and .Invoke - if that is even possible?
The server is started like that:
Server server = new Server(PORT);
server.RunAsync();
in .RunAsync() i just iterate over the network devices and set them to listening and invoke an event that the server has started, this also writes into the GUI however without any issue.
public async Task RunAsync()
{
GetNetworkDevicesReady(Port);
await Task.Factory.StartNew(() =>
{
Parallel.ForEach(networkListeners, (listener) =>
{
Write.Info($"LISTENING ON {listener.LocalEndpoint}");
listener.Start();
});
});
IsRunning = true;
OnServerStarted?.Invoke(this, networkListeners.Where(l=>l.Active).ToList());
}
The code below is registered on the Form.Load event and does not cause a Cross-Thread exception when writing "SERVER STARTED" in the textbox.
server.OnServerStarted += (s, a) =>
{
consoleWindow1.Event("SERVER STARTED", $"{Environment.NewLine}\t{string.Join($"{Environment.NewLine}\t", a.Select(x=>x.LocalEndpoint))}");
consoleWindow1.Event("WAITING FOR PENDING CONNECTIONS");
server.WaitForConnectionsAsync();
};
And this is the code which runs indefinite until a cancellation token is triggered:
public async Task WaitForConnectionsAsync()
{
waitingForConnectionsToken = new CancellationTokenSource();
await (waitinfConnectionTaks=Task.Factory.StartNew(async () =>
{
while (!waitingForConnectionsToken.IsCancellationRequested)
{
foreach (var listener in networkListeners)
{
if (waitingForConnectionsToken.IsCancellationRequested) break;
if (!listener.Active)
{
continue;
}
if (listener.Pending())
{
try
{
TcpClient connection = await listener.AcceptTcpClientAsync();
//TODO: need to send it synchronised, since this causes a Cross-Thread when using WinForms
OnPendingConnection?.Invoke(this, connection);
}
catch (ObjectDisposedException x)
{
Write.Error(x.ToString());
}
}
}
}
}));
}
I know I can use the textbox .InvokeRequired and .Invoke on the GUI but I have the feeling that the server should throw the event in a way the GUI doesn't cause a Cross-Thread exception.
Is there a way to invoke the eventhandler in that "infinite task" without causing this exception?
Thanks to the comments and a good portion of sleep I solved my issue by changing the WaitForConnectionsAsync to the following code:
List<TcpClient> connections = new List<TcpClient>();
public async Task WaitForConnectionsAsync()
{
await (waitinfConnectionTaks = Task.Factory.StartNew(async () =>
{
//REMOVED LOOP
// while (!waitingForConnectionsToken.IsCancellationRequested)
{
foreach (var listener in networkListeners)
{
if (waitingForConnectionsToken.IsCancellationRequested) break;
if (!listener.Active)
{
continue;
}
if (listener.Pending())
{
try
{
TcpClient connection = await listener.AcceptTcpClientAsync();
//RETAIN CONNECTIONS IN A LIST
connections.Add(connection);
}
catch (ObjectDisposedException x)
{
Write.Error(x.ToString());
}
}
}
}
}));
//ITERATE OVER CONNECTIONS
foreach (var connection in connections)
{
//INVOKE EVENT
OnPendingConnection?.Invoke(this, connection);
}
//CLEAR THE LIST
connections.Clear();
//RESTART THE TASK
if(!waitingForConnectionsToken.IsCancellationRequested)
WaitForConnectionsAsync();
}
So Basically i am catching all pending connections into a list, once the work has completed, I run over the list, fire the event with each connection, clear the list and then start the task again. This code change doesn't throw the Cross-Thread exception anymore.
An improvement i could add now is to accept a collection in the event instead a single connection.
If you have any improvements or better practice suggestions, please let me know.
I am working on a solution that uses web socket protocol to notify client (web browser) when some event happened on the server (MVC Core web app). I use Microsoft.AspNetCore.WebSockets nuget.
Here is my client-side code:
$(function () {
var socket = new WebSocket("ws://localhost:61019/data/openSocket");
socket.onopen = function () {
$(".socket-status").css("color", "green");
}
socket.onmessage = function (message) {
$("body").append(document.createTextNode(message.data));
}
socket.onclose = function () {
$(".socket-status").css("color", "red");
}
});
When this view is loaded the socket request is immediately sent to the MVC Core application. Here is the controller action:
[Route("data")]
public class DataController : Controller
{
[Route("openSocket")]
[HttpGet]
public ActionResult OpenSocket()
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
WebSocket socket = HttpContext.WebSockets.AcceptWebSocketAsync().Result;
if (socket != null && socket.State == WebSocketState.Open)
{
while (!HttpContext.RequestAborted.IsCancellationRequested)
{
var response = string.Format("Hello! Time {0}", System.DateTime.Now.ToString());
var bytes = System.Text.Encoding.UTF8.GetBytes(response);
Task.Run(() => socket.SendAsync(new System.ArraySegment<byte>(bytes),
WebSocketMessageType.Text, true, CancellationToken.None));
Thread.Sleep(3000);
}
}
}
return new StatusCodeResult(101);
}
}
This code works very well. WebSocket here is used exclusively for sending and doesn't receive anything. The problem, however, is that the while loop keeps holding the DataController thread until cancellation request is detected.
Web socket here is bound to the HttpContext object. As soon as HttpContext for the web request is destroyed the socket connection is immediately closed.
Question 1: Is there any way that socket can be preserved outside of the controller thread?
I tried putting it into a singleton that lives in the MVC Core Startup class that is running on the main application thread. Is there any way to keep the socket open or establish connection again from within the main application thread rather than keep holding the controller thread with a while loop?
Even if it is deemed to be OK to hold up controller thread for socket connection to remain open, I cannot think of any good code to put inside the OpenSocket's while loop. What do you think about having a manual reset event in the controller and wait for it to be set inside the while loop within OpenSocket action?
Question 2: If it is not possible to separate HttpContext and WebSocket objects in MVC, what other alternative technologies or development patterns can be utilized to achieve socket connection reuse? If anyone thinks that SignalR or a similar library has some code allowing to have socket independent from HttpContext, please share some example code. If someone thinks there is a better alternative to MVC for this particular scenario, please provide an example, I do not mind switching to pure ASP.NET or Web API, if MVC does not have capabilities to handle independent socket communication.
Question 3: The requirement is to keep socket connection alive or be able to reconnect until explicit timeout or cancel request by the user. The idea is that some independent event happens on the server that triggers established socket to send data.
If you think that some technology other than web sockets would be more useful for this scenario (like HTML/2 or streaming), could you please describe the pattern and frameworks you would use?
P.S. Possible solution would be to send AJAX requests every second to ask if there was new data on the server. This is the last resort.
After lengthy research I ended up going with a custom middleware solution. Here is my middleware class:
public class SocketMiddleware
{
private static ConcurrentDictionary<string, SocketMiddleware> _activeConnections = new ConcurrentDictionary<string, SocketMiddleware>();
private string _packet;
private ManualResetEvent _send = new ManualResetEvent(false);
private ManualResetEvent _exit = new ManualResetEvent(false);
private readonly RequestDelegate _next;
public SocketMiddleware(RequestDelegate next)
{
_next = next;
}
public void Send(string data)
{
_packet = data;
_send.Set();
}
public async Task Invoke(HttpContext context)
{
if (context.WebSockets.IsWebSocketRequest)
{
string connectionName = context.Request.Query["connectionName"]);
if (!_activeConnections.Any(ac => ac.Key == connectionName))
{
WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
if (socket == null || socket.State != WebSocketState.Open)
{
await _next.Invoke(context);
return;
}
Thread sender = new Thread(() => StartSending(socket));
sender.Start();
if (!_activeConnections.TryAdd(connectionName, this))
{
_exit.Set();
await _next.Invoke(context);
return;
}
while (true)
{
WebSocketReceiveResult result = socket.ReceiveAsync(new ArraySegment<byte>(new byte[1]), CancellationToken.None).Result;
if (result.CloseStatus.HasValue)
{
_exit.Set();
break;
}
}
SocketHandler dummy;
_activeConnections.TryRemove(key, out dummy);
}
}
await _next.Invoke(context);
string data = context.Items["Data"] as string;
if (!string.IsNullOrEmpty(data))
{
string name = context.Items["ConnectionName"] as string;
SocketMiddleware connection = _activeConnections.Where(ac => ac.Key == name)?.Single().Value;
if (connection != null)
{
connection.Send(data);
}
}
}
private void StartSending(WebSocket socket)
{
WaitHandle[] events = new WaitHandle[] { _send, _exit };
while (true)
{
if (WaitHandle.WaitAny(events) == 1)
{
break;
}
if (!string.IsNullOrEmpty(_packet))
{
SendPacket(socket, _packet);
}
_send.Reset();
}
}
private void SendPacket(WebSocket socket, string packet)
{
byte[] buffer = Encoding.UTF8.GetBytes(packet);
ArraySegment<byte> segment = new ArraySegment<byte>(buffer);
Task.Run(() => socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None));
}
}
This middleware is going to run on every request. When Invoke is called it checks if it is a web socket request. If it is, the middleware checks if such connection was already opened and if it wasn't, the handshake is accepted and the middleware adds it to the dictionary of connections. It's important that the dictionary is static so that it is created only once during application lifetime.
Now if we stop here and move up the pipeline, HttpContext will eventually get destroyed and, since the socket is not properly encapsulated, it will be closed too. So we must keep the middleware thread running. It is done by asking socket to receive some data.
You may ask why we need to receive anything if the requirement is just to send? The answer is that it is the only way to reliably detect client disconnecting. HttpContext.RequestAborted.IsCancellationRequested works only if you constantly send within the while loop. If you need to wait for some server event on a WaitHandle, cancellation flag is never true. I tried to wait for HttpContext.RequestAborted.WaitHandle as my exit event, but it is never set either. So we ask socket to receive something and if that something sets CloseStatus.HasValue to true, we know that client disconnected. If we receive something else (client side code is unsafe) we will ignore it and start receiving again.
Sending is done in a separate thread. The reason is the same, it's not possible to detect disconnection if we wait on the main middleware thread. To notify the sender thread that client disconnected we use _exit synchronization variable. Remember, it is fine to have private members here since SocketMiddleware instances are saved in a static container.
Now, how do we actually send anything with this set up? Let's say an event occurs on the server and some data becomes available. For simplicity sake, lets assume this data arrives inside normal http request to some controller action. SocketMiddleware will run for every request, but since it is not web socket request, _next.Invoke(context) is called and the request reaches controller action which may look something like this:
[Route("ProvideData")]
[HttpGet]
public ActionResult ProvideData(string data, string connectionName)
{
if (!string.IsNullOrEmpty(data) && !string.IsNullOrEmpty(connectionName))
{
HttpContext.Items.Add("ConnectionName", connectionName);
HttpContext.Items.Add("Data", data);
}
return Ok();
}
Controller populates Items collection which is used to share data between components. Then the pipeline returns to the SocketMiddleware again where we check whether there is anything interesting inside the context.Items. If there is we select respective connection from the dictionary and call its Send() method that sets data string and sets _send event and allows single run of the while loop inside the sender thread.
And voila, we a have socket connection that sends on server side event. This example is very primitive and is there just to illustrate the concept. Of course, to use this middleware you will need to add the following lines in your Startup class before you add MVC:
app.UseWebSockets();
app.UseMiddleware<SocketMiddleware>();
Code is very strange and hopefully we'll be able to write something much nicer when SignalR for dotnetcore is finally out. Hopefully this example will be useful for someone. Comments and suggestions are welcome.
i'm trying to use this protocol and already have 2 clients (one to publish and another to subscribe) and a broker working.
My question is i want to implement a reconnect feature in the subscribe client because the wifi signal is unstable and don't want to manually restart the client every single time, how can i accomplish this?
You can use the ConnectionClosed event to detect when a disconnect happens.
I then start a task that will try to reconnect the client.
Something like:
private async Task TryReconnectAsync(CancellationToken cancellationToken)
{
var connected = _client.IsConnected;
while (!connected && !cancellationToken.IsCancellationRequested)
{
try
{
_client.Connect(_clientId);
}
catch
{
_logger.Log(LogLevel.Warn, "No connection to...{0}",_serverIp);
}
connected = _client.IsConnected;
await Task.Delay(10000, cancellationToken);
}
}
Not perfect, but will do the job.
For those looking for a simple connection persistence here is my solution used.
When you want to start your mqtt connection call Task.Run(() => PersistConnectionAsync()); and note that static bool _tryReconnectMQTT should be defined at the class (or desired) scope level.
private async Task PersistConnectionAsync()
{
var connected = _mqttClient.IsConnected;
while (_tryReconnectMQTT)
{
if (!connected)
{
try
{
_mqttClient.Connect(_clientId);
}
catch
{
Debug.WriteLine("failed reconnect");
}
}
await Task.Delay(1000);
connected = _mqttClient.IsConnected;
}
}
I would also suggest using the last will and testament to know how long your client was down for and when. Replace _mqttClient.Connect(_clientId); with the following.
_mqttClient.Connect(_clientId,
null, null,
false,
MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, //aws
true,
$"/my/topic/{_clientId}connectionstatus",
"{\"message\":\"disconnected\"}",
true,
60);
Publish a connected message to the same topic with similar message after the connection statement to ensure you know all the times you were disconnected. Using AWS rules engine you would be able to send a notification on connection status, it is even possible to notify yourself if the duration between the reconnect is over a certain time.
The m2mqtt client has a .ConnectionClosed event you can subscribe your reconnect method to.
I am implementing a piece of software that reads a list of ids from a message queue. Once some come through, I would like to pass each one through a socket to a third party application, that will then process it and return a value back once it's done.
If the third party app takes too long to reply, I want to report this and maybe even close the connection.
Furthermore, this should run asynchronously, that is, once the messages are read from the queue, a separate task is started to handle it being sent to the socket and any subsequent communication.
Following this I have created a class that spawns a task and sends an exception after a timeout threshold.
public async Task Run(Action action, int timeoutInSeconds)
{
try
{
await Task.Run(action).TimeoutAfter(timeoutInSeconds);
}
catch (TimeoutException te)
{
//add error capture here or retry
}
}
public static async Task TimeoutAfter(this Task task, int timeoutInSeconds)
{
if (task == await Task.WhenAny(task, Task.Delay(timeoutInSeconds*1000)))
{
await task;
}
else
{
throw new TimeoutException(string.Format("Task {0} timed out after {1} seconds", task.Id, timeoutInSeconds));
}
}
Next I created another class to asynchronously listen to connections.
public class SocketListener
{
...
public async void Listen(Action action)
{
//initialization code
var listener = new TcpListener(ipAddress, Port);
listener.Start(numberOfConnections);
while (true)
{
try
{
//wait for client to connect
var client = await listener.AcceptTcpClientAsync();
//do something once client is connected
var task = new TaskWithTimeout();
await task.Run(() => action, 10);
}
catch (Exception ex)
{
// Log error
throw;
}
}
}
...
}
Here, after the client connects successfully, I want to call a method that will handle communication between server and client. If the client takes too long to respond, the TaskWithTimeout should throw an exception and move on.
My thought process was to call SocketListener once I read from the queue
public void ProcessQueue() {
//initialize SocketListener
listener.Listen(MethodToHandleCommunication)
...
}
Now I am a bit stuck. Preferably, SocketListener should be able to handle any type of communication, and that's why I thought I'd pass the Action as a parameter, so that I can determine what method I want to run from outside (by this I mean that if in the future I need to pass different data to the client, I would be able to reuse this code). However with this approach, I cannot even pass the client object back to the action.
In general I feel like I'm taking the wrong approach, and I am sure there's a better and more efficient way of doing what I want. As you can see I'm fairly new to parallel programming in general. I am a bit frustrated with this and would greatly appreciate any help or insight from SO