-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathWebSocketBuilder.cs
63 lines (54 loc) · 2.18 KB
/
WebSocketBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System.Net.WebSockets;
using System.Security.Cryptography.X509Certificates;
namespace k8s
{
/// <summary>
/// The <see cref="WebSocketBuilder"/> creates a new <see cref="WebSocket"/> object which connects to a remote WebSocket.
/// </summary>
/// <remarks>
/// By default, this uses the .NET <see cref="ClientWebSocket"/> class, but you can inherit from this class and change it to
/// use any class which inherits from <see cref="WebSocket"/>, should you want to use a third party framework or mock the requests.
/// </remarks>
public class WebSocketBuilder
{
protected ClientWebSocket WebSocket { get; private set; } = new ClientWebSocket();
public WebSocketBuilder()
{
}
public ClientWebSocketOptions Options => WebSocket.Options;
public virtual WebSocketBuilder SetRequestHeader(string headerName, string headerValue)
{
WebSocket.Options.SetRequestHeader(headerName, headerValue);
return this;
}
public virtual WebSocketBuilder AddClientCertificate(X509Certificate2 certificate)
{
WebSocket.Options.ClientCertificates.Add(certificate);
return this;
}
public WebSocketBuilder ExpectServerCertificate(X509Certificate2Collection serverCertificate)
{
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
Options.RemoteCertificateValidationCallback
= (sender, certificate, chain, sslPolicyErrors) =>
{
return Kubernetes.CertificateValidationCallBack(sender, serverCertificate, certificate, chain, sslPolicyErrors);
};
#endif
return this;
}
public WebSocketBuilder SkipServerCertificateValidation()
{
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
Options.RemoteCertificateValidationCallback
= (sender, certificate, chain, sslPolicyErrors) => true;
#endif
return this;
}
public virtual async Task<WebSocket> BuildAndConnectAsync(Uri uri, CancellationToken cancellationToken)
{
await WebSocket.ConnectAsync(uri, cancellationToken).ConfigureAwait(false);
return WebSocket;
}
}
}