Example #1
0
        public async Task Get()
        {
            var webSocketManager = _httpContextAccessor.HttpContext.WebSockets;

            if (webSocketManager.IsWebSocketRequest == false)
            {
                return;
            }
            var webSocket = await webSocketManager.AcceptWebSocketAsync();

            var connectionOpen = true;

            while (connectionOpen)
            {
                (var connectionClosed, var message) = await ReceiveMessage(webSocket);

                connectionOpen = connectionClosed == false;
                if (message == "REQUEST_RATE_BTCEUR")
                {
                    var btcEuroRate = await _bitcoinRatesService.RetrieveBtcEuroRate(CancellationToken.None);

                    var responseMessage = $"{DateTime.UtcNow} BTC = {btcEuroRate} EUR";
                    var responseBuffer  = Encoding.UTF8.GetBytes(responseMessage);
                    await webSocket.SendAsync(new ArraySegment <byte>(responseBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }
 public async Task Get()
 {
     await _responseStreamer.StreamResponse(
         async (write, cancellationToken) =>
     {
         while (true)
         {
             if (cancellationToken.IsCancellationRequested)
             {
                 break;
             }
             var btcEuroRate = await _bitcoinRatesService.RetrieveBtcEuroRate(cancellationToken);
             await write($"{DateTime.UtcNow} BTC = {btcEuroRate} EUR");
             await Task.Delay(2000, cancellationToken);
         }
     });
 }