Skip to content

Commit

Permalink
Reconnect on failed ws sends, improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Trolldemorted committed Jul 9, 2018
1 parent fd80fea commit 436be61
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions Signal-Windows.Lib/SignalWebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ private void WebSocket_Closed(IWebSocket sender, WebSocketClosedEventArgs args)

private void WebSocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
Logger.LogTrace("WebSocket_MessageReceived()");
try
{
using (var data = args.GetDataStream())
Expand All @@ -75,6 +76,7 @@ public void Close(ushort code, string reason)

public async Task ConnectAsync()
{
Logger.LogTrace("ConnectAsync()");
var locked = await SemaphoreSlim.WaitAsync(0, Token); // ensure no threads are reconnecting at the same time
if (locked)
{
Expand All @@ -83,6 +85,7 @@ public async Task ConnectAsync()
try
{
CreateMessageWebSocket();
Logger.LogTrace("WebSocket.ConnectAsync()");
await WebSocket.ConnectAsync(SignalWSUri).AsTask(Token);
SemaphoreSlim.Release();
break;
Expand All @@ -100,6 +103,10 @@ public async Task ConnectAsync()
}
}
}
else
{
Logger.LogTrace("ConnectAsync() not reconnecting: Reconnect in progress");
}
}

public void Dispose()
Expand All @@ -109,11 +116,21 @@ public void Dispose()

public async Task SendMessage(byte[] data)
{
using (var dataWriter = new DataWriter(WebSocket.OutputStream))
Logger.LogTrace("SendMessage()");
try
{
using (var dataWriter = new DataWriter(WebSocket.OutputStream))
{
dataWriter.WriteBytes(data);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
}
catch (OperationCanceledException) { }
catch (Exception e)
{
dataWriter.WriteBytes(data);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
Logger.LogError($"SendMessage() failed: {e.Message}\n{e.StackTrace}");
var t = Task.Run(ConnectAsync);
}
}
}
Expand Down

0 comments on commit 436be61

Please sign in to comment.