This repository has been archived by the owner on Sep 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.cs
207 lines (173 loc) · 5.98 KB
/
Client.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
#if !UNITY_WEBGL || UNITY_EDITOR
using System;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Ninja.WebSockets;
namespace Mirror.Websocket
{
public class Client
{
public event Action Connected;
public event Action<ArraySegment<byte>> ReceivedData;
public event Action Disconnected;
public event Action<Exception> ReceivedError;
const int MaxMessageSize = 1024 * 256;
WebSocket webSocket;
CancellationTokenSource cancellation;
public bool NoDelay = true;
public bool Connecting { get; set; }
public bool IsConnected { get; set; }
Uri uri;
public async void Connect(Uri uri)
{
// not if already started
if (webSocket != null)
{
// paul: exceptions are better than silence
ReceivedError?.Invoke(new Exception("Client already connected"));
return;
}
this.uri = uri;
// We are connecting from now until Connect succeeds or fails
Connecting = true;
WebSocketClientOptions options = new WebSocketClientOptions()
{
NoDelay = true,
KeepAliveInterval = TimeSpan.Zero,
SecWebSocketProtocol = "binary"
};
cancellation = new CancellationTokenSource();
WebSocketClientFactory clientFactory = new WebSocketClientFactory();
try
{
using (webSocket = await clientFactory.ConnectAsync(uri, options, cancellation.Token))
{
CancellationToken token = cancellation.Token;
IsConnected = true;
Connecting = false;
Connected?.Invoke();
await ReceiveLoop(webSocket, token);
}
}
catch (ObjectDisposedException)
{
// No error, the client got closed
}
catch (Exception ex)
{
ReceivedError?.Invoke(ex);
}
finally
{
Disconnect();
Disconnected?.Invoke();
}
}
public bool enabled;
async Task ReceiveLoop(WebSocket webSocket, CancellationToken token)
{
byte[] buffer = new byte[MaxMessageSize];
while (true)
{
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), token);
if (!enabled)
{
await WaitForEnabledAsync();
}
if (result == null)
break;
if (result.MessageType == WebSocketMessageType.Close)
break;
// we got a text or binary message, need the full message
ArraySegment<byte> data = await ReadFrames(result, webSocket, buffer);
if (data.Count == 0)
break;
try
{
ReceivedData?.Invoke(data);
}
catch (Exception exception)
{
ReceivedError?.Invoke(exception);
}
}
}
async Task WaitForEnabledAsync()
{
while (!enabled)
{
await Task.Delay(10);
}
}
public bool ProcessClientMessage()
{
// message in standalone client don't use queue to process
return false;
}
// a message might come splitted in multiple frames
// collect all frames
async Task<ArraySegment<byte>> ReadFrames(WebSocketReceiveResult result, WebSocket webSocket, byte[] buffer)
{
int count = result.Count;
while (!result.EndOfMessage)
{
if (count >= MaxMessageSize)
{
string closeMessage = string.Format("Maximum message size: {0} bytes.", MaxMessageSize);
await webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, closeMessage, CancellationToken.None);
ReceivedError?.Invoke(new WebSocketException(WebSocketError.HeaderError));
return new ArraySegment<byte>();
}
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, count, MaxMessageSize - count), CancellationToken.None);
count += result.Count;
}
return new ArraySegment<byte>(buffer, 0, count);
}
public void Disconnect()
{
cancellation?.Cancel();
// only if started
if (webSocket != null)
{
// close client
webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
webSocket = null;
Connecting = false;
IsConnected = false;
}
}
// send the data or throw exception
public async void Send(ArraySegment<byte> segment)
{
if (webSocket == null)
{
ReceivedError?.Invoke(new SocketException((int)SocketError.NotConnected));
return;
}
try
{
await webSocket.SendAsync(segment, WebSocketMessageType.Binary, true, cancellation.Token);
}
catch (Exception ex)
{
Disconnect();
ReceivedError?.Invoke(ex);
}
}
public override string ToString()
{
if (IsConnected)
{
return $"Websocket connected to {uri}";
}
if (Connecting)
{
return $"Websocket connecting to {uri}";
}
return "";
}
}
}
#endif