44 public async Task<bool>
Connect(Uri endpoint,
int attemptTries = 3)
46 Debug.Log(
"Connecting websocket to endpoint " + endpoint.ToString());
55 var tokenSource =
new System.Threading.CancellationTokenSource();
56 tokenSource.CancelAfter(10000);
58 string connectionMessage =
"";
60 int currentAttempt = 0;
61 while(currentAttempt < attemptTries)
69 if(!(ex is WebSocketException))
73 currentAttempt = attemptTries;
76 connectionMessage = ex.Message;
80 if (
WebSocket.State == WebSocketState.Open)
86 Debug.LogWarning(
"Failed to connect on attempt " + currentAttempt +
".");
87 await Task.Delay(5000);
90 Debug.Log(
"Web socket connection attempt has occured.");
91 if (
WebSocket.State != WebSocketState.Open)
97 Debug.Log(
"Web socket connection was successful.");
104 return WebSocket.State == WebSocketState.Open;
161 async
void Send(
byte[] message)
163 Debug.Log(
"Sending data of length " + message.Length);
164 bool socketClosed = (WebSocket.State != WebSocketState.Open);
165 bool messageSent =
true;
171 var buffer =
new ArraySegment<Byte>(message, 0, message.Length);
172 var cancelTokenSource =
new System.Threading.CancellationTokenSource();
173 cancelTokenSource.CancelAfter(10000);
174 await
WebSocket.SendAsync(buffer, WebSocketMessageType.Text,
true, cancelTokenSource.Token);
178 Debug.LogWarning(
"Websocket send stopped with exception of type " + ex.GetType().Name);
180 if (ex is OperationCanceledException ||
WebSocket.CloseStatus.HasValue)
182 Debug.LogWarning(
"Websocket closed because " + ex.Message);
184 else if (ex is WebSocketException)
201 bool socketClosed = (WebSocket.State != WebSocketState.Open);
203 byte[] receiveBuffer =
new byte[2048];
204 int bufferOffset = 0;
205 int maxPacketSize = 256;
206 while (!socketClosed)
208 bool finishedReceiving =
false;
209 while (!finishedReceiving)
213 ArraySegment<byte> bytesReceived =
new ArraySegment<byte>(receiveBuffer, bufferOffset, maxPacketSize);
216 WebSocketReceiveResult result = await
WebSocket.ReceiveAsync(bytesReceived, System.Threading.CancellationToken.None);
219 Debug.Log(
"Data: " + Encoding.UTF8.GetString(receiveBuffer, bufferOffset, result.Count));
221 bufferOffset += result.Count;
222 if (result.EndOfMessage)
224 finishedReceiving =
true;
226 Array.Clear(receiveBuffer, 0, 2048);
232 Debug.LogWarning(
"Websocket receive stopped with exception of type " + ex.GetType().Name);
234 if (ex is OperationCanceledException ||
WebSocket.CloseStatus.HasValue)
236 Debug.LogWarning(
"Websocket closed.");
237 finishedReceiving = socketClosed =
true;
239 else if(ex is WebSocketException)
241 Debug.LogWarning(
"Websocket closed because " + ex.Message);
251 socketClosed =
WebSocket.CloseStatus.HasValue;