Reputation: 1630
I 'd like to make a websocket client to connect to a third-party web socket server.
I am using ClientWebSocket Class:
public WSClientService(ClientWebSocket client, ILogger<WSClientService> logger)
{
_client = client;
_logger = logger;
}
For receiving messages i use this method:
public async Task GetMessagesAsync()
{
while (_client.State == WebSocketState.Open)
{
var chunkSize = 1024 * 4;
var buffer = new ArraySegment<byte>(new byte[chunkSize]);
do
{
WebSocketReceiveResult result;
using var ms = new MemoryStream();
try
{
do
{
//here throws exception
result = await _client.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
} while (!result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
ms.Seek(0, SeekOrigin.Begin);
using var reader = new StreamReader(ms, Encoding.UTF8);
var message = await reader.ReadToEndAsync();
_logger.LogInformation(message);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
} while (_client.State != WebSocketState.Aborted);
}
}
But for some messages i get this exception message :
The WebSocket received a frame with one or more reserved bits set
I noticed that this occurs probably by some compression because i can receive small messages. The exception thrown when calling this result = await _client.ReceiveAsync(buffer, CancellationToken.None);
Does anybody knows how to solve this problem?
Upvotes: 0
Views: 1343
Reputation: 1630
The solution came with .net 6 release. Well the problem occured because there was no way to add compression in built-in ClientWebSocket in .net 5 and back (Except if someone would create an extension method for compression). Now with .net 6 there is a new option named DangerousDeflateOptions
. This adds the corresponding header as well.
_ws.Options.DangerousDeflateOptions = new WebSocketDeflateOptions
{
ServerContextTakeover = false,
ClientMaxWindowBits = 15 // this is the default value
};
await _ws.ConnectAsync(new Uri(_url), token).ConfigureAwait(false);
Upvotes: 0