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 <WebSocketReceiveResult> ReadMessage(IWebSocketWrapper webSocket, ArraySegment <byte> receivedDataBuffer, MemoryStream memoryStream) { WebSocketReceiveResult webSocketReceiveResult; long length = 0; do { webSocketReceiveResult = await webSocket.ReceiveAsync(receivedDataBuffer, CancellationToken.None) .ConfigureAwait(false); length += webSocketReceiveResult.Count; await memoryStream.WriteAsync(receivedDataBuffer.Array, receivedDataBuffer.Offset, webSocketReceiveResult.Count) .ConfigureAwait(false); }while (!webSocketReceiveResult.EndOfMessage); return(webSocketReceiveResult); }
public async Task <byte[]> ReceiveMessageAsync(CancellationToken cancellationToken) { var bytes = new byte[UInt16.MaxValue]; // Max size of Sc2Api message is unknown, however size of efficient websocket fits in 2 bytes https://stackoverflow.com/a/14119129/2235675 var finished = false; var index = 0; while (!finished) { var result = await _webSocketWrapper.ReceiveAsync(new ArraySegment <byte>(bytes, index, UInt16.MaxValue), cancellationToken); if (result.MessageType != WebSocketMessageType.Binary) { throw new Exception("Expected binary message type."); } finished = result.EndOfMessage; if (!finished) { bytes = IncreaseByteArraySize(bytes); } index += result.Count; } return(bytes[0..index]);