public async Task RunAsync() { try { /*We define a certain constant which will represent * size of received data. It is established by us and * we can set any value. We know that in this case the size of the sent * data is very small. */ const int maxMessageSize = 2048; // Buffer for received bits. ArraySegment <byte> receivedDataBuffer = new ArraySegment <byte>(new byte[maxMessageSize]); MemoryStream memoryStream = new MemoryStream(); // Checks WebSocket state. while (mWebSocket.IsConnected) { // Reads data. WebSocketReceiveResult webSocketReceiveResult; long length = 0; do { webSocketReceiveResult = await mWebSocket.ReceiveAsync(receivedDataBuffer, mCancellationTokenSource.Token) .ConfigureAwait(false); length += webSocketReceiveResult.Count; await memoryStream.WriteAsync(receivedDataBuffer.Array, receivedDataBuffer.Offset, webSocketReceiveResult.Count, mCancellationTokenSource.Token) .ConfigureAwait(false); } while (!webSocketReceiveResult.EndOfMessage); // If input frame is cancelation frame, send close command. if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close) { this.RaiseConnectionClosed(); await mWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, mCancellationTokenSource.Token) .ConfigureAwait(false); } else { memoryStream.Position = 0; OnNewMessage(memoryStream); } memoryStream.Position = 0; memoryStream.SetLength(0); } } catch (Exception ex) { RaiseConnectionError(ex); } }
private async Task CloseWebSocket() { try { await mWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None) .ConfigureAwait(false); } catch (Exception ex) { mLogger.WarnException("Failed sending a close message to client", ex); } }
private async Task CloseWebSocket() { try { await mWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None) .ConfigureAwait(false); } catch (WebSocketException ex) when(ex.WebSocketErrorCode == WebSocketError.InvalidState) { mLogger.DebugException("Failed closing the websocket as it was already aborted", ex); } catch (Exception ex) { mLogger.WarnException("Failed sending a close message to client", ex); } }