HTTP2
- Multiplexing
- Server push
- Header compression
ref site:
- HTTP/2 vs. HTTP/1.1: How do they affect web performance?
- HTTP/2: the difference between HTTP/1.1, benefits and how to use it
os and browsers support
- Windows 10 1607+
- TLS 1.2+
- browsers
Note: recommended to use Chrome/FireFox
WebSockets
- Accept a WebSocket connection as an asynchronous operation
HttpListenerContext.AcceptWebSocketAsync() - Receives data from the WebSocket connection asynchronously
WebSocket.ReceiveAsync() - Sends data over the WebSocket connection asynchronously
WebSocket.SendAsync() - Closes the WebSocket connection as an asynchronous operation
CloseAsync
Enable WebSocket
- default
app.UseWebSockets()
- options
var webSocketOptions = new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromMinutes(2)
};
app.UseWebSockets(webSocketOptions);
Accept WebSocket requests
if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
}
receive messages
var buffer = new byte[1024 * 4];
var receiveResult = await webSocket.ReceiveAsync(
new ArraySegment<byte>(buffer), CancellationToken.None);
ArraySegment
Array version of substring()
String[] names = { "Adam", "Bruce", "Charles", "Daniel",
"Ebenezer", "Francis", "Gilbert",
"Henry", "Irving", "John", "Karl",
"Lucian", "Michael" };
var partNames = new ArraySegment<string>(names, 2, 5);
The example displays the following output:
// Charles
// Daniel
// Ebenezer
// Francis
// Gilbert
Send messages
var memory = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(str));
await webSocket.SendAsync(
memory,
0, // text message
0, // none
CancellationToken.None);
ReadOnlyMemory
var memory = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(str));
MessageType
- Binary
1
The message is in binary format.
- Close
2
A receive has completed because a close message was received.
- Text
0
The message is clear text.
WebSocketMessageFlags
- DisableCompression
2
Disables compression for the message if compression has been enabled for the WebSocket instance.
- EndOfMessage
1
Indicates that the data in “buffer” is the last part of a message.
- None
0
None
close
await webSocket.CloseAsync(
1000, // NormalClosure
"normal closure",
CancellationToken.None);
WebSocketCloseStatus
Fields:
1000, 1001, 1002, 1003, 1005, 1007, 1008, 1009, 1010, 1100
Samples
- WebSocketController
Operation WebSocket - Program.cs
Enable WebSocket