doghappy / socket.io-client-csharp

socket.io-client implemention for .NET
MIT License
729 stars 125 forks source link

ConnectAsync overload with CancellationToken parameter and NuGet package update #379

Closed Aspher0 closed 1 month ago

Aspher0 commented 2 months ago

Closes #377

I've added a new overload for the ConnectAsync method that now allows the user to pass a CancellationToken. This lets the user cancel the connection at any time given before the server has connected. It prevents the user from waiting a specific amount of time before the connection timeout runs out, and allows for a quick and easy cancellation.

A usage example would be :

private static SemaphoreSlim ConnectionSemaphore = new SemaphoreSlim(1);
private static CancellationTokenSource? CancellationTokenSource;

// ...

CancellationTokenSource?.Cancel();
CancellationTokenSource = new CancellationTokenSource();
var cancellationToken = CancellationTokenSource.Token;

try
{
    await ConnectionSemaphore.WaitAsync(cancellationToken);

    var options = new SocketIOOptions
    {
        Reconnection = true,
        ConnectionTimeout = TimeSpan.FromSeconds(30),
        ReconnectionAttempts = 0,
    };

    Client = new SocketIOClient.SocketIO(serverURL, options);

    try
    {
        await Client.ConnectAsync(cancellationToken);
    }
    catch (Exception ex)
    {
        if (ex is OperationCanceledException)
        {
            // Connection canceled
        }
        else
        {
            // Couldn't connect to server, or else
        }
    }
}
finally
{
    ConnectionSemaphore.Release();
}

I have also updated the NuGet packages since there was a high, known vulnerability.