public async Task SendJSON(dynamic JsonRequest) { var jsonRequest = JsonConvert.SerializeObject(JsonRequest); var outBuffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(jsonRequest)); SendBuffer.Add(outBuffer); if (SendBuffer.Count > 1) { return; } while (SendBuffer.Count > 0) { try { await Socket.SendAsync(SendBuffer[0], WebSocketMessageType.Text, true, CancellationToken.None); SendBuffer.RemoveAt(0); } catch (Exception ex) { if (AllSockets.Contains(this)) { AllSockets.Remove(this); } SendBuffer.Clear(); throw ex; } } }
public async Task HandleSocket(HttpContext Context, WebSocket WS) { try { AllSockets.Add(this); Socket = WS; var buffer = new byte[1024 * 10]; WebSocketReceiveResult result = await WS.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); await ParseMessage(result, buffer); while (!Socket.CloseStatus.HasValue) { buffer = new byte[1024 * 10]; result = await WS.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); await ParseMessage(result, buffer); } if (AllSockets.Contains(this)) { AllSockets.Remove(this); } if (CurrentChat != null) { await LeaveChat(CurrentChat); await SendUserListUpdate(CurrentChat); } await WS.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } catch (Exception Ex) { if (AllSockets.Contains(this)) { AllSockets.Remove(this); } if (CurrentChat != null) { await LeaveChat(CurrentChat); await SendUserListUpdate(CurrentChat); } Utilities.WriteToLog(Ex); } }