Ejemplo n.º 1
0
        //async void is bad but there is no other option in this scenario.
        //It is equivalent to event handler, caller is not interested in task
        private async void StartListening()
        {
            var receiveBuffer = new byte[4096 * 20];

            while (_webSocket.State == WebSocketState.Open)
            {
                var totalBytes = new byte[0];
                WebSocketReceiveResult result;
                do
                {
                    result = await _webSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                    }
                    else
                    {
                        var existingSize = totalBytes.Length;
                        totalBytes = new byte[existingSize + result.Count];
                        Buffer.BlockCopy(receiveBuffer, 0, totalBytes, existingSize, result.Count);
                    }
                } while (!result.EndOfMessage);

                var payLoad = _deserializer.DeserializePayload(totalBytes);
                _dataStream.OnNext(payLoad);
            }
        }