-
Notifications
You must be signed in to change notification settings - Fork 51
/
SocketClient.cs
283 lines (240 loc) · 9.21 KB
/
SocketClient.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
using DevelopmentInProgress.Socket.Messages;
using DevelopmentInProgress.Socket.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace DevelopmentInProgress.Socket.Client
{
/// <summary>
/// Send and receives <see cref="WebSocket"/> requests to a <see cref="SocketServer"/>
/// </summary>
public class SocketClient : IDisposable
{
private readonly ClientWebSocket clientWebSocket;
private readonly Dictionary<string, Action<Message>> registeredMethods;
private bool disposed;
/// <summary>
/// Raised when an exception is thrown.
/// </summary>
public event EventHandler<Exception> Error;
/// <summary>
/// Raised when the <see cref="ClientWebSocket"/> is closed.
/// </summary>
public event EventHandler Closed;
/// <summary>
/// Gets the connection id.
/// </summary>
public string ConnectionId { get; private set; }
/// <summary>
/// Gets the uri of the <see cref="SocketServer"/>.
/// </summary>
public Uri Uri { get; private set; }
/// <summary>
/// Gets the client identifier.
/// </summary>
public string ClientId { get; private set; }
/// <summary>
/// Gets the <see cref="ClientWebSocket"/> state.
/// </summary>
public WebSocketState State { get { return clientWebSocket.State; } }
/// <summary>
/// Creates a new instance of the <see cref="SocketClient"/>.
/// </summary>
/// <param name="uri">The url of the <see cref="SocketServer"/>. Http and Https will be converted to ws.</param>
/// <param name="clientId">The client side identifier.</param>
public SocketClient(Uri uri, string clientId)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (uri.ToString().StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
Uri = new Uri($"ws{uri.ToString().Substring(5)}");
}
else if (uri.ToString().StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
Uri = new Uri($"ws{uri.ToString().Substring(4)}");
}
else if (uri.ToString().StartsWith("ws:https://", StringComparison.OrdinalIgnoreCase))
{
Uri = new Uri(uri.ToString());
}
else
{
throw new ArgumentException($"Uri not supported : {uri}");
}
ClientId = clientId;
clientWebSocket = new ClientWebSocket();
registeredMethods = new Dictionary<string, Action<Message>>();
}
/// <summary>
/// Close and dispose of the <see cref="ClientWebSocket"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (clientWebSocket.State == WebSocketState.Open)
{
clientWebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).Wait();
}
clientWebSocket.Dispose();
disposed = true;
}
/// <summary>
/// Close and dispose of the <see cref="ClientWebSocket"/>.
/// </summary>
/// <returns>A <see cref="Task"/>.</returns>
public async Task DisposeAsync()
{
if (disposed)
{
return;
}
if (clientWebSocket.State == WebSocketState.Open)
{
await clientWebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false);
}
clientWebSocket.Dispose();
disposed = true;
}
/// <summary>
/// Register a <see cref="Action"/> to be invoked when receiving a message from the <see cref="SocketServer"/>.
/// </summary>
/// <param name="methodName"></param>
/// <param name="handler"></param>
public void On(string methodName, Action<Message> handler)
{
registeredMethods.Add(methodName, handler);
}
/// <summary>
/// Open a <see cref="WebSocket"/> connection with the <see cref="SocketServer"/>.
/// </summary>
/// <returns>A <see cref="Task"/>.</returns>
public async Task StartAsync()
{
await StartAsync(string.Empty).ConfigureAwait(false);
}
/// <summary>
/// Open a <see cref="WebSocket"/> connection with the <see cref="SocketServer"/>.
/// </summary>
/// <param name="data"></param>
/// <returns>A <see cref="Task"/>.</returns>
public async Task StartAsync(string data)
{
var collection = HttpUtility.ParseQueryString(string.Empty);
collection["clientId"] = ClientId;
collection["data"] = data;
var uriBuilder = new UriBuilder(Uri) { Query = collection.ToString() };
await clientWebSocket.ConnectAsync(uriBuilder.Uri, CancellationToken.None).ConfigureAwait(false);
RunReceiving();
}
/// <summary>
/// Send a mesage from to the <see cref="SocketServer"/> to be routed to the receipient.
/// </summary>
/// <param name="message">The <see cref="Message"/> to send.</param>
/// <returns>A <see cref="Task"/>.</returns>
public async Task SendMessageAsync(Message message)
{
if (clientWebSocket.State.Equals(WebSocketState.Open))
{
var json = JsonConvert.SerializeObject(message);
var bytes = Encoding.UTF8.GetBytes(json);
await clientWebSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false);
}
}
/// <summary>
/// Close the <see cref="ClientWebSocket"/>.
/// </summary>
/// <returns>A <see cref="Task"/>.</returns>
public async Task StopAsync()
{
if (clientWebSocket.State.Equals(WebSocketState.Open))
{
await clientWebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false);
}
}
private void OnError(Exception exception)
{
var error = Error;
error.Invoke(this, exception);
}
private void OnClose()
{
var closed = Closed;
closed.Invoke(this, EventArgs.Empty);
}
private void RunReceiving()
{
Task.Run(async () =>
{
try
{
await Receiving().ConfigureAwait(false);
}
catch(WebSocketException ex)
{
OnError(ex);
}
});
}
private async Task Receiving()
{
var buffer = new byte[1024 * 4];
var messageBuilder = new StringBuilder();
while (clientWebSocket.State.Equals(WebSocketState.Open))
{
WebSocketReceiveResult webSocketReceiveResult;
messageBuilder.Clear();
do
{
try
{
webSocketReceiveResult = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).ConfigureAwait(false);
}
catch (WebSocketException)
{
if (clientWebSocket.State.Equals(WebSocketState.Aborted))
{
break;
}
throw;
}
if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
{
await clientWebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false);
OnClose();
break;
}
else if (webSocketReceiveResult.MessageType.Equals(WebSocketMessageType.Text))
{
messageBuilder.Append(Encoding.UTF8.GetString(buffer, 0, webSocketReceiveResult.Count));
}
}
while (!webSocketReceiveResult.EndOfMessage);
if(messageBuilder.Length > 0)
{
var json = messageBuilder.ToString();
var message = JsonConvert.DeserializeObject<Message>(json);
if (registeredMethods.TryGetValue(message.MethodName, out Action<Message> method))
{
method.Invoke(message);
}
}
}
}
}
}