-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathWebSocketClient.cs
More file actions
143 lines (132 loc) · 6.16 KB
/
Copy pathWebSocketClient.cs
File metadata and controls
143 lines (132 loc) · 6.16 KB
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
using System;
using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClientExample
{
public static class WebSocketClient
{
private static ClientWebSocket Socket;
private static BlockingCollection<string> KeystrokeQueue = new BlockingCollection<string>();
private static CancellationTokenSource SocketLoopTokenSource;
private static CancellationTokenSource KeystrokeLoopTokenSource;
public static async Task StartAsync(string wsUri)
=> await StartAsync(new Uri(wsUri));
public static async Task StartAsync(Uri wsUri)
{
Console.WriteLine($"Connecting to server {wsUri.ToString()}");
SocketLoopTokenSource = new CancellationTokenSource();
KeystrokeLoopTokenSource = new CancellationTokenSource();
try
{
Socket = new ClientWebSocket();
await Socket.ConnectAsync(wsUri, CancellationToken.None);
_ = Task.Run(() => SocketProcessingLoopAsync().ConfigureAwait(false));
_ = Task.Run(() => KeystrokeTransmitLoopAsync().ConfigureAwait(false));
}
catch (OperationCanceledException)
{
// normal upon task/token cancellation, disregard
}
}
public static async Task StopAsync()
{
Console.WriteLine($"\nClosing connection");
KeystrokeLoopTokenSource.Cancel();
if (Socket == null || Socket.State != WebSocketState.Open) return;
// close the socket first, because ReceiveAsync leaves an invalid socket (state = aborted) when the token is cancelled
var timeout = new CancellationTokenSource(Program.CLOSE_SOCKET_TIMEOUT_MS);
try
{
// after this, the socket state which change to CloseSent
await Socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", timeout.Token);
// now we wait for the server response, which will close the socket
while (Socket.State != WebSocketState.Closed && !timeout.Token.IsCancellationRequested) ;
}
catch (OperationCanceledException)
{
// normal upon task/token cancellation, disregard
}
// whether we closed the socket or timed out, we cancel the token causing RecieveAsync to abort the socket
SocketLoopTokenSource.Cancel();
// the finally block at the end of the processing loop will dispose and null the Socket object
}
public static WebSocketState State
{
get => Socket?.State ?? WebSocketState.None;
}
public static void QueueKeystroke(string message)
=> KeystrokeQueue.Add(message);
private static async Task SocketProcessingLoopAsync()
{
var cancellationToken = SocketLoopTokenSource.Token;
try
{
var buffer = WebSocket.CreateClientBuffer(4096, 4096);
while (Socket.State != WebSocketState.Closed && !cancellationToken.IsCancellationRequested)
{
var receiveResult = await Socket.ReceiveAsync(buffer, cancellationToken);
// if the token is cancelled while ReceiveAsync is blocking, the socket state changes to aborted and it can't be used
if (!cancellationToken.IsCancellationRequested)
{
// the server is notifying us that the connection will close; send acknowledgement
if (Socket.State == WebSocketState.CloseReceived && receiveResult.MessageType == WebSocketMessageType.Close)
{
Console.WriteLine($"\nAcknowledging Close frame received from server");
KeystrokeLoopTokenSource.Cancel();
await Socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Acknowledge Close frame", CancellationToken.None);
}
// display text or binary data
if (Socket.State == WebSocketState.Open && receiveResult.MessageType != WebSocketMessageType.Close)
{
string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
if (message.Length > 1) message = "\n" + message + "\n";
Console.Write(message);
}
}
}
Console.WriteLine($"Ending processing loop in state {Socket.State}");
}
catch (OperationCanceledException)
{
// normal upon task/token cancellation, disregard
}
catch (Exception ex)
{
Program.ReportException(ex);
}
finally
{
KeystrokeLoopTokenSource.Cancel();
Socket.Dispose();
Socket = null;
}
}
private static async Task KeystrokeTransmitLoopAsync()
{
var cancellationToken = KeystrokeLoopTokenSource.Token;
while(!cancellationToken.IsCancellationRequested)
{
try
{
await Task.Delay(Program.KEYSTROKE_TRANSMIT_INTERVAL_MS, cancellationToken);
if(!cancellationToken.IsCancellationRequested && KeystrokeQueue.TryTake(out var message))
{
var msgbuf = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
await Socket.SendAsync(msgbuf, WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None);
}
}
catch (OperationCanceledException)
{
// normal upon task/token cancellation, disregard
}
catch (Exception ex)
{
Program.ReportException(ex);
}
}
}
}
}