private async Task HandleWebSocketAsync(WebSocket websocket) { try { if (OnConnect != null) OnConnect.Invoke(websocket); while (websocket.IsConnected) { var message = await websocket.ReadStringAsync(CancellationToken.None) .ConfigureAwait(false); if (message != null && OnMessage != null) OnMessage.Invoke(websocket, message); } if (OnDisconnect != null) OnDisconnect.Invoke(websocket); } catch (Exception ex) { if (OnError != null) OnError.Invoke(websocket, ex); } finally { websocket.Dispose(); } }
private static async Task EchoAllIncomingMessagesAsync(WebSocket webSocket, CancellationToken cancellation) { Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' connected."); var sw = new Stopwatch(); try { while (webSocket.IsConnected && !cancellation.IsCancellationRequested) { try { var messageText = await webSocket.ReadStringAsync(cancellation).ConfigureAwait(false); if (messageText == null) { break; // webSocket is disconnected } Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' recived: " + messageText + "."); sw.Restart(); messageText = WebSocketHandler(messageText); await webSocket.WriteStringAsync(messageText, cancellation).ConfigureAwait(false); Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' sent: " + messageText + "."); sw.Stop(); } catch (TaskCanceledException) { break; } catch (Exception readWriteError) { Console.WriteLine("An error occurred while reading/writing echo message.", readWriteError); await webSocket.CloseAsync().ConfigureAwait(false); } } } finally { webSocket.Dispose(); Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' disconnected."); } }
static async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation) { try { while (ws.IsConnected && !cancellation.IsCancellationRequested) { String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false); Log("Message: " + msg); ws.WriteString(msg); } } catch (Exception aex) { Log("Error Handling connection: " + aex.GetBaseException().Message); try { ws.Close(); } catch { } } finally { ws.Dispose(); } }
static async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation) { try { IWebSocketLatencyMeasure l = ws as IWebSocketLatencyMeasure; PerformanceCounters.Connected.Increment(); while (ws.IsConnected && !cancellation.IsCancellationRequested) { String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false); PerformanceCounters.MessagesIn.Increment(); ws.WriteString(msg); PerformanceCounters.MessagesOut.Increment(); PerformanceCounters.Delay.IncrementBy(l.Latency.Ticks * Stopwatch.Frequency / 10000); PerformanceCounters.DelayBase.Increment(); } } catch (TaskCanceledException) { } catch (Exception aex) { Log("Error Handling connection: " + aex.GetBaseException().Message); try { ws.Close(); } catch { } } finally { ws.Dispose(); PerformanceCounters.Connected.Decrement(); } }
private static async Task WaitForAuthenticateMessage(WebSocket ws, CancellationToken cancellation) { while (ws.IsConnected && !cancellation.IsCancellationRequested) { string json = await ws.ReadStringAsync(cancellation).ConfigureAwait(false); if (json == null) continue; var auth = JsonConvert.DeserializeObject<AuthenticateMessage>(json); if (!string.IsNullOrEmpty(auth.Id)) { Interlocked.Increment(ref PerformanceCounters.Authenticated); ws.WriteStringAsync(auth.Id + "_OK", cancellation).Wait(cancellation); Console.WriteLine("Authenticated " + PerformanceCounters.Authenticated); break; } } }
private static async Task WaitForMessage(WebSocket ws, CancellationToken cancellation) { while (ws.IsConnected && !cancellation.IsCancellationRequested) { string msg = await ws.ReadStringAsync(cancellation); if (msg == null) continue; ws.WriteString(msg + " back from WebSocketTest"); } }
async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation) { try { while (ws.IsConnected && !cancellation.IsCancellationRequested) { // Get the JSON Message. String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false); if (msg != null) { // Convert the JSON String to a dictionary Dictionary<string, dynamic> msgDict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(msg); ; // If the dictionary contains a uniqueId, the message is a log-in request. if (msgDict.ContainsKey("uniqueId")) { this.HandleMatchQueue(ws, msgDict); } // Message doesn't contain a UniqueId field. else { // Make sure the websocket is in a match if (wsToIdDictionary.ContainsKey(ws)) { idToPlayerDictionary[wsToIdDictionary[ws]].currentMatch.AcceptMessage(ws, msgDict); } } } } } catch (Exception aex) { Console.WriteLine("Error Handling connection: " + aex.GetBaseException().Message); try { ws.Close(); } catch { } } // Theoretically, this happens when the ws disconnected, right? finally { if (wsToIdDictionary.ContainsKey(ws)) { if (attackerQueue.Contains(wsToIdDictionary[ws])) { string tempId = wsToIdDictionary[ws]; // loop ends when we find the id matching the ws we want to remove. while (tempId != attackerQueue.Peek()) { attackerQueue.Enqueue(attackerQueue.Dequeue()); } attackerQueue.Dequeue(); } } if (wsToIdDictionary.ContainsKey(ws)) { if (defenderQueue.Contains(wsToIdDictionary[ws])) { string tempId = wsToIdDictionary[ws]; // loop ends when we find the id matching the ws we want to remove. while (tempId != defenderQueue.Peek()) { defenderQueue.Enqueue(attackerQueue.Dequeue()); } defenderQueue.Dequeue(); } } if (wsToIdDictionary.ContainsKey(ws)) { if (idToPlayerDictionary.ContainsKey(wsToIdDictionary[ws])) { idToPlayerDictionary[wsToIdDictionary[ws]].currentMatch.ws_disconnected(ws); } } if (ws.IsConnected) { ws.Dispose(); } } }