Skip to content

Commit

Permalink
When disconnecting, prepare for a new connection.
Browse files Browse the repository at this point in the history
  • Loading branch information
FrostyCoolSlug committed Aug 9, 2024
1 parent 2c1f2c6 commit fba53f9
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions UtilityClient/Native/WebsocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ private async Task ReceiveMessageTask()

case WebSocketMessageType.Binary:
default:
// This wont occur with the Utility, but we need to trigger DisconnectAsync to perform tidying up!
await _client.CloseAsync(WebSocketCloseStatus.ProtocolError, "Only Text is supported.", CancellationToken.None);
this.OnDisconnected?.Invoke(this, "Connection closed because server tried to send binary or invalid message.");
break;
Expand All @@ -94,8 +95,8 @@ private async Task ConnectionTask()

case WebSocketState.Aborted:
case WebSocketState.Closed:
if (this._isConnected) this.OnDisconnected?.Invoke(this, "Connection closed.");
this._isConnected = false;
// Trigger an internal disconnect to clean resources.
Task.Run(DisconnectAsync);

Check warning on line 99 in UtilityClient/Native/WebsocketClient.cs

View workflow job for this annotation

GitHub Actions / Build for Linux

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Check warning on line 99 in UtilityClient/Native/WebsocketClient.cs

View workflow job for this annotation

GitHub Actions / Build for Windows

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
break;

default:
Expand Down Expand Up @@ -126,7 +127,10 @@ public async Task<bool> ConnectAsync(Uri uri)

public async Task DisconnectAsync()
{
await this._client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
// Only attempt to close the socket if it's not already closed
if (this._client.State != WebSocketState.Aborted && this._client.State != WebSocketState.Closed) {
await this._client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
this.OnDisconnected?.Invoke(this, "Connection closed.");

this._cancellationTokenSource.Cancel();
Expand All @@ -140,6 +144,15 @@ public async Task DisconnectAsync()

this._receiveMessageTask.Dispose();
this._connectionTask.Dispose();

// Dispose of, and create a new client / Token for future connections
this._client.Dispose();
this._client = new();
this._cancellationTokenSource.Dispose();
this._cancellationTokenSource = new();

// Flag the connection as disconnected
this._isConnected = false;
}

public async Task SendMessage(string message)
Expand Down

0 comments on commit fba53f9

Please sign in to comment.