-
Notifications
You must be signed in to change notification settings - Fork 1
/
CoolWebSocketClient.cs
227 lines (192 loc) · 7.2 KB
/
CoolWebSocketClient.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
using System;
using System.Buffers;
using System.Data.Common;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#nullable disable
namespace CoolWebSocketClient
{
public enum CoolWebSocketMessageType
{
Text,
Binary,
Close
}
public enum CoolWebSocketError
{
Success = 0,
InvalidMessageType = 1,
Faulted = 2,
NativeError = 3,
NotAWebSocket = 4,
UnsupportedVersion = 5,
UnsupportedProtocol = 6,
HeaderError = 7,
ConnectionClosedPrematurely = 8,
InvalidState = 9
}
public enum CoolWebSocketCloseStatus
{
NormalClosure = 1000,
EndpointUnavailable = 1001,
ProtocolError = 1002,
InvalidMessageType = 1003,
Empty = 1005,
InvalidPayloadData = 1007,
PolicyViolation = 1008,
MessageTooBig = 1009,
MandatoryExtension = 1010,
InternalServerError = 1011
}
public delegate void CoolWebSocketOpenEvent();
public delegate void CoolWebSocketErrorEvent(CoolWebSocketError errorCode, string errorMessage);
public delegate void CoolWebSocketCloseEvent(CoolWebSocketCloseStatus closeStatus, string closeMessage);
public delegate void CoolWebSocketMessageEvent(CoolWebSocketMessageType messageType, byte[] message);
public sealed class CoolWebSocket : IDisposable
{
private readonly ClientWebSocket WebSocket = new();
public WebSocketState State => WebSocket.State;
public ClientWebSocketOptions Options => WebSocket.Options;
public string SubProtocol => WebSocket.SubProtocol;
public Uri Uri { get; private set; }
private readonly CancellationTokenSource CancellationTokenSource = new();
private CancellationToken CancellationToken => CancellationTokenSource.Token;
public bool IsOpen => State == WebSocketState.Open || State == WebSocketState.Connecting;
#region Events
public event CoolWebSocketOpenEvent OnOpen;
public event CoolWebSocketErrorEvent OnError;
public event CoolWebSocketCloseEvent OnClose;
public event CoolWebSocketMessageEvent OnMessage;
private void ThrowIfCloseError()
{
if (IsOpen || !WebSocket.CloseStatus.HasValue) return;
OnClose?.Invoke((CoolWebSocketCloseStatus)WebSocket.CloseStatus.Value, WebSocket.CloseStatusDescription);
}
#endregion
#region Connection
private Thread Thread;
public async Task Open(Uri uri)
{
if (IsOpen) return;
Uri = uri;
try
{
await WebSocket.ConnectAsync(uri, CancellationToken);
Thread = new(new ThreadStart(async () =>
{
while (IsOpen) await Poll();
})) { Name = "CoolWebSocketClientThread" };
Thread.Start();
OnOpen?.Invoke();
}
catch (WebSocketException exception)
{
OnError?.Invoke((CoolWebSocketError)exception.WebSocketErrorCode, exception.Message);
ThrowIfCloseError();
}
catch (Exception exception)
{
OnError?.Invoke((CoolWebSocketError)WebSocketError.Faulted, exception.Message);
ThrowIfCloseError();
}
}
public async Task Close(
CoolWebSocketCloseStatus closeStatus = CoolWebSocketCloseStatus.NormalClosure,
string closeMessage = null
) {
if (!IsOpen) return;
try
{
await WebSocket.CloseAsync((WebSocketCloseStatus)closeStatus, closeMessage, CancellationToken);
OnClose?.Invoke(closeStatus, closeMessage);
}
catch (WebSocketException exception)
{
OnError?.Invoke((CoolWebSocketError)exception.WebSocketErrorCode, exception.Message);
ThrowIfCloseError();
return;
}
catch (Exception exception)
{
OnError?.Invoke((CoolWebSocketError)WebSocketError.Faulted, exception.Message);
ThrowIfCloseError();
return;
}
finally
{
CancellationTokenSource.Cancel();
}
}
#endregion
#region Sending
private async Task InternalSend(dynamic data, WebSocketMessageType messageType = WebSocketMessageType.Binary)
{
if (!IsOpen) return;
try
{
await WebSocket.SendAsync(data, messageType, true, CancellationToken);
}
catch (WebSocketException exception)
{
OnError?.Invoke((CoolWebSocketError)exception.WebSocketErrorCode, exception.Message);
ThrowIfCloseError();
}
catch (Exception ex)
{
OnError?.Invoke((CoolWebSocketError)WebSocketError.Faulted, ex.Message);
ThrowIfCloseError();
}
}
public async Task Send(ReadOnlyMemory<byte> data) => await InternalSend(data);
public async Task Send(ArraySegment<byte> data) => await InternalSend(data);
public async Task Send(byte[] data) => await InternalSend(new ReadOnlyMemory<byte>(data));
public async Task Send(string text)
=> await InternalSend(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text);
#endregion
#region Receiving
private const int PollBufferSize = 16384;
private readonly MemoryStream MemoryStream = new();
private async Task Poll()
{
// keep writing until eom
WebSocketReceiveResult result = null;
do
{
// rent a temporary buffer
byte[] buffer = ArrayPool<byte>.Shared.Rent(PollBufferSize);
try
{
result = await WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken);
MemoryStream.Write(buffer, 0, result.Count);
if (result.EndOfMessage)
{
OnMessage?.Invoke((CoolWebSocketMessageType)result.MessageType, MemoryStream.ToArray());
MemoryStream.SetLength(0);
}
}
catch (WebSocketException exception)
{
OnError?.Invoke((CoolWebSocketError)exception.WebSocketErrorCode, exception.Message);
ThrowIfCloseError();
break;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
} while (result != null && !result.EndOfMessage);
}
public string ReadString(ArraySegment<byte> message) => Encoding.UTF8.GetString(message);
#endregion
public void Dispose()
{
CancellationTokenSource?.Cancel();
WebSocket?.Dispose();
CancellationTokenSource?.Dispose();
MemoryStream?.Dispose();
}
}
}