diff --git a/dotnet/src/webdriver/BiDi/Communication/Transport/WebSocketTransport.cs b/dotnet/src/webdriver/BiDi/Communication/Transport/WebSocketTransport.cs index f8a76f208a8d0..52cd5c0ffa7f2 100644 --- a/dotnet/src/webdriver/BiDi/Communication/Transport/WebSocketTransport.cs +++ b/dotnet/src/webdriver/BiDi/Communication/Transport/WebSocketTransport.cs @@ -16,9 +16,10 @@ public class WebSocketTransport(Uri _uri) : ITransport, IDisposable private readonly ClientWebSocket _webSocket = new(); private readonly ArraySegment _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); } @@ -32,8 +33,9 @@ public async Task ReceiveAsJsonAsync(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); @@ -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(buffer), WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false); + await _webSocket.SendAsync(new ArraySegment(buffer), WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false); + } + finally + { + _socketSendSemaphoreSlim.Release(); + } } public void Dispose()