-
Notifications
You must be signed in to change notification settings - Fork 0
/
WSClient.cs
137 lines (126 loc) · 4.17 KB
/
WSClient.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
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
namespace Speechly.Tools
{
struct SendQueueItem {
public ArraySegment<byte> payload;
public WebSocketMessageType type;
public SendQueueItem(ArraySegment<byte> payload, WebSocketMessageType type) {
this.payload = payload;
this.type = type;
}
}
public class WsClient : IDisposable
{
public delegate void ResponseReceivedDelegate(MemoryStream inputStream);
public ResponseReceivedDelegate OnResponseReceived = (inputStream) => { };
private ClientWebSocket WS;
private CancellationTokenSource CTS;
private BlockingCollection<SendQueueItem> SendQueue = new BlockingCollection<SendQueueItem>();
private Task sendTask;
private Task receiveTask;
public int ReceiveBufferSize { get; set; } = 8192;
public async Task ConnectAsync(string url, string authToken)
{
if (WS != null) {
if (WS.State == WebSocketState.Open) return;
else WS.Dispose();
}
WS = new ClientWebSocket();
WS.Options.AddSubProtocol(authToken);
if (CTS != null) {
CTS.Dispose();
}
CTS = new CancellationTokenSource();
await WS.ConnectAsync(new Uri(url), CTS.Token);
receiveTask = Task.Run(ReceiveLoop, CancellationToken.None);
sendTask = Task.Run(SendLoop, CancellationToken.None);
}
public async Task DisconnectAsync()
{
if (CTS != null) {
CTS.Cancel();
await Task.WhenAll(new []{sendTask, receiveTask});
CTS.Dispose();
CTS = null;
}
if (WS != null) {
if (WS.State == WebSocketState.Open) {
await WS.CloseOutputAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);
await WS.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
WS.Dispose();
WS = null;
}
}
public void SendText(string text)
{
SendQueue.Add(new SendQueueItem(
new ArraySegment<byte>(Encoding.UTF8.GetBytes(text)),
WebSocketMessageType.Text
));
}
public void SendBytes(ArraySegment<byte> byteArraySegment)
{
SendQueue.Add(new SendQueueItem(
byteArraySegment,
WebSocketMessageType.Binary
));
}
private async Task ReceiveLoop()
{
var loopToken = CTS.Token;
MemoryStream outputStream = null;
WebSocketReceiveResult receiveResult = null;
var buffer = new byte[ReceiveBufferSize];
try {
while (!loopToken.IsCancellationRequested) {
outputStream = new MemoryStream(ReceiveBufferSize);
do {
receiveResult = await WS.ReceiveAsync(new ArraySegment<byte>(buffer), CTS.Token);
if (receiveResult.MessageType != WebSocketMessageType.Close) {
outputStream.Write(buffer, 0, receiveResult.Count);
} else {
Logger.Log($"Web connection closed due to {receiveResult.CloseStatus}");
break;
}
} while (!loopToken.IsCancellationRequested && !receiveResult.EndOfMessage);
if (!loopToken.IsCancellationRequested && receiveResult.MessageType != WebSocketMessageType.Close) {
outputStream.Position = 0;
OnResponseReceived(outputStream);
}
outputStream.Dispose();
}
}
catch (OperationCanceledException) {
// normal upon task/token cancellation, disregard
} finally {
outputStream?.Dispose();
}
}
private async Task SendLoop()
{
while (!CTS.Token.IsCancellationRequested) {
try {
if(!CTS.Token.IsCancellationRequested && SendQueue.TryTake(out SendQueueItem item, -1, CTS.Token))
{
await WS.SendAsync(item.payload, item.type, endOfMessage: true, CTS.Token);
}
}
catch (OperationCanceledException) {
// normal upon task/token cancellation, disregard
}
catch {
Logger.LogError("Error in SendLoop");
throw;
}
}
}
public void Dispose() => DisconnectAsync().Wait();
}
}