Skip to content

Commit

Permalink
[dotnet] [bidi] Fix web socket communication for .net framework
Browse files Browse the repository at this point in the history
Related to SeleniumHQ#14537
  • Loading branch information
nvborisenko committed Sep 26, 2024
1 parent 419484d commit 7d1d0e0
Showing 1 changed file with 18 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ public class WebSocketTransport(Uri _uri) : ITransport, IDisposable
private readonly ClientWebSocket _webSocket = new();
private readonly ArraySegment<byte> _receiveBuffer = new(new byte[1024 * 8]);

private readonly SemaphoreSlim _socketSendSemaphoreSlim = new(1, 1);

public async Task ConnectAsync(CancellationToken cancellationToken)
{
_webSocket.Options.SetBuffer(_receiveBuffer.Count, _receiveBuffer.Count, _receiveBuffer);
await _webSocket.ConnectAsync(_uri, cancellationToken).ConfigureAwait(false);
}

Expand All @@ -32,8 +33,9 @@ public async Task<T> ReceiveAsJsonAsync<T>(JsonSerializerOptions jsonSerializerO
{
result = await _webSocket.ReceiveAsync(_receiveBuffer, cancellationToken).ConfigureAwait(false);

await ms.WriteAsync(_receiveBuffer.Array!, _receiveBuffer.Offset, result.Count).ConfigureAwait(false);
} while (!result.EndOfMessage);
await ms.WriteAsync(_receiveBuffer.Array!, _receiveBuffer.Offset, result.Count, cancellationToken).ConfigureAwait(false);
}
while (!result.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);

Expand All @@ -51,12 +53,21 @@ public async Task SendAsJsonAsync(Command command, JsonSerializerOptions jsonSer
{
var buffer = JsonSerializer.SerializeToUtf8Bytes(command, typeof(Command), jsonSerializerOptions);

if (_logger.IsEnabled(LogEventLevel.Trace))
await _socketSendSemaphoreSlim.WaitAsync(cancellationToken);

try
{
_logger.Trace($"BiDi SND >> {buffer.Length} > {Encoding.UTF8.GetString(buffer)}");
}
if (_logger.IsEnabled(LogEventLevel.Trace))
{
_logger.Trace($"BiDi SND >> {buffer.Length} > {Encoding.UTF8.GetString(buffer)}");
}

await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false);
await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false);
}
finally
{
_socketSendSemaphoreSlim.Release();
}
}

public void Dispose()
Expand Down

0 comments on commit 7d1d0e0

Please sign in to comment.