Exemplo n.º 1
0
        public Task <IConnectionState> Run(Action <ServerSentEvent> donothing, CancellationToken cancelToken)
        {
            IWebRequester requester = _webRequesterFactory.Create();
            var           taskResp  = requester.Get(_url, _tokenService, _headers);

            return(taskResp.ContinueWith <IConnectionState>(tsk =>
            {
                if (tsk.Status == TaskStatus.RanToCompletion && !cancelToken.IsCancellationRequested)
                {
                    IServerResponse response = tsk.Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return new ConnectedState(response, _webRequesterFactory, _headers, _tokenService, _logger);
                    }
                    else
                    {
                        _logger.LogInformation("Failed to connect to: " + _url.ToString() + response ?? (" Http statuscode: " + response.StatusCode));
                    }
                }
                else
                {
                    _logger.LogDebug("Task Status {@Status}: {Reason}", tsk.Status, ExceptionDetails.InnermostMessage(tsk.Exception));
                }

                return new DisconnectedState(_url, _webRequesterFactory, _headers, _tokenService, _logger);
            }));
        }
Exemplo n.º 2
0
        public Task <IConnectionState> Run(Action <ServerSentEvent> msgReceived, CancellationToken cancelToken)
        {
            Task <IConnectionState> t = new Task <IConnectionState>(() =>
            {
                try
                {
                    var stream    = _response.GetResponseStream();
                    byte[] buffer = new byte[1024 * 32];
                    var taskRead  = stream.ReadAsync(buffer, 0, buffer.Length, cancelToken);

                    taskRead.Wait(cancelToken);

                    if (!cancelToken.IsCancellationRequested)
                    {
                        var bytesRead = taskRead.Result;

                        if (bytesRead > 0) // stream has not reached the end yet
                        {
                            _logger.LogTrace("ReadCallback {bytesRead} bytesRead", bytesRead);
                            string text    = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                            text           = _remainingText + text;
                            string[] lines = StringSplitter.SplitIntoLines(text, out _remainingText);
                            foreach (string line in lines)
                            {
                                if (cancelToken.IsCancellationRequested)
                                {
                                    break;
                                }

                                if (string.IsNullOrEmpty(line.Trim()) && _sse != null)
                                {
                                    _logger.LogDebug("Message received");
                                    msgReceived(_sse);
                                    _sse = null;
                                }
                                else if (line.StartsWith(":"))
                                {
                                    _logger.LogDebug("A comment was received: {line}", line);
                                }
                                else
                                {
                                    string fieldName  = String.Empty;
                                    string fieldValue = String.Empty;
                                    if (line.Contains(':'))
                                    {
                                        int index  = line.IndexOf(':');
                                        fieldName  = line.Substring(0, index);
                                        fieldValue = line.Substring(index + 1).TrimStart();
                                    }
                                    else
                                    {
                                        fieldName = line;
                                    }

                                    if (String.Compare(fieldName, "event", true) == 0)
                                    {
                                        _sse           = _sse ?? new ServerSentEvent();
                                        _sse.EventType = fieldValue;
                                    }
                                    else if (String.Compare(fieldName, "data", true) == 0)
                                    {
                                        _sse      = _sse ?? new ServerSentEvent();
                                        _sse.Data = fieldValue + '\n';
                                    }
                                    else if (String.Compare(fieldName, "id", true) == 0)
                                    {
                                        _sse             = _sse ?? new ServerSentEvent();
                                        _sse.LastEventId = fieldValue;
                                    }
                                    else if (String.Compare(fieldName, "retry", true) == 0)
                                    {
                                        int parsedRetry;
                                        if (int.TryParse(fieldValue, out parsedRetry))
                                        {
                                            _sse       = _sse ?? new ServerSentEvent();
                                            _sse.Retry = parsedRetry;
                                        }
                                    }
                                    else
                                    {
                                        _logger.LogInformation("An unknown line was received: {line}", line);
                                    }
                                }
                            }

                            if (!cancelToken.IsCancellationRequested)
                            {
                                return(this);
                            }
                        }
                        else // end of the stream reached
                        {
                            _logger.LogDebug("No bytes read. End of stream.");
                        }
                    }
                }

                catch (Exception ex)
                {
                    _logger.LogDebug("Error: {message} {inner}", ex.Message, ExceptionDetails.InnermostMessage(ex));
                    //_logger.LogTrace(ex, "ConnectedState.Run");
                }
                //stream.Dispose()
                //stream.Close();
                //mResponse.Close();
                //mResponse.Dispose();
                return(new DisconnectedState(_response.ResponseUri, _webRequesterFactory, _headers, _tokenService, _logger));
            });

            t.Start();
            return(t);
        }