Reputation: 55
I am using .NET 6 to establish a WebSocket connection and I am using "ClientWebSocket" to use this.I am aware that the Server supports the "permessage-deflate" from the following handshake.
GET / HTTP/1.1
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 4Qecg52c4NaUM7RDCcW9/g==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: domainname:64901
HTTP/1.1 101 WebSocket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: +lpWMhWJ1SpnmxcxRtx/Bk+k5q8=
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits=15
So in .NET when I want to enable the "permessage-deflate"
What options on "ClientWebSocket" are to be enabled?
What are the values the "WebSocketDeflateOptions" object to set for "permessage-deflate" if required?
Does adding request header "Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits"
alone will do the compression?
Does compression/decompression need to be done before/after sending/receiving content manually or handled internally by ClientWebSocket object?
Need an example where "permessage-deflate" is enabled in .NET 6
Upvotes: 1
Views: 191
Reputation: 8368
In WebSockets, compression is typically requested by the client using the WebSocketDeflateOptions. The server accepts this request and negotiates the compression during the WebSocket handshake.The server doesn't need to explicitly set compression options.
Client
ClientWebSocket clientWebSocket = new ClientWebSocket();
clientWebSocket.Options.DangerousDeflateOptions = new WebSocketDeflateOptions
{
ClientMaxWindowBits = 15, // Max window size for client compression (15 bits is the maximum allowed)
ServerMaxWindowBits = 15, // Max window size for server compression
ClientContextTakeover = true, // Enable client-side context takeover (preserve compression context between messages)
ServerContextTakeover = true // Enable server-side context takeover
};
await clientWebSocket.ConnectAsync(new Uri("ws://127.0.0.1:8085/"), CancellationToken.None);
byte[] receiveBuffer = new byte[2048];
WebSocketReceiveResult receiveResult = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer),
CancellationToken.None);
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count);
Console.WriteLine(receivedMessage);
Upvotes: 0