当前位置: 首页>>代码示例>>C#>>正文


C# IConnection.OnError方法代码示例

本文整理汇总了C#中IConnection.OnError方法的典型用法代码示例。如果您正苦于以下问题:C# IConnection.OnError方法的具体用法?C# IConnection.OnError怎么用?C# IConnection.OnError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IConnection的用法示例。


在下文中一共展示了IConnection.OnError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OpenConnection

        private void OpenConnection(IConnection connection, string data, dotnet2::System.Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;

            var url = (reconnecting ? connection.Url : connection.Url + "connect");

            Action<IRequest> prepareRequest = PrepareRequest(connection);

            EventSignal<IResponse> signal;

            if (shouldUsePost(connection))
            {
                url += GetReceiveQueryString(connection, data);

                Debug.WriteLine(string.Format("SSE: POST {0}", url));

                signal = _httpClient.PostAsync(url, request =>
                                                        {
                                                            prepareRequest(request);
                                                            request.Accept = "text/event-stream";
                                                        }, new Dictionary<string, string> {{"groups", GetSerializedGroups(connection)}});
            }
            else
            {
                url += GetReceiveQueryStringWithGroups(connection, data);

                Debug.WriteLine(string.Format("SSE: GET {0}", url));

                signal = _httpClient.GetAsync(url, request =>
                {
                    prepareRequest(request);

                    request.Accept = "text/event-stream";
                });
            }

            signal.Finished += (sender,e)=> {
                if (e.Result.IsFaulted)
                {
                    var exception = e.Result.Exception.GetBaseException();
                    if (!IsRequestAborted(exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref _initializedCalled, 1) == 0)
                        {
                            errorCallback(exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }

                    if (reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var response = e.Result;
                    var stream = response.GetResponseStream();
                    var reader = new AsyncStreamReader(stream,
                                                       connection,
                                                       () =>
                                                       {
                                                           if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                                                           {
                                                               initializeCallback();
                                                           }
                                                       },
                                                       () =>
                                                       {
                                                           response.Close();

                                                           Reconnect(connection, data);
                                                       });

                    if (reconnecting)
                    {
                        // Raise the reconnect event if the connection comes back up
                        connection.OnReconnected();
                    }

                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            };

            if (initializeCallback != null)
            {
                Thread.Sleep(ConnectionTimeout);
                if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
//.........这里部分代码省略.........
开发者ID:robink-teleopti,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例2: OpenConnection

        private void OpenConnection(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;

            var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);

            Action<IRequest> prepareRequest = PrepareRequest(connection);

            #if NET35
            Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "SSE: GET {0}", (object)url));
            #else
            Debug.WriteLine("SSE: GET {0}", (object)url);
            #endif

            _httpClient.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    var exception = task.Exception.Unwrap();
                    if (!ExceptionHelper.IsRequestAborted(exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref _initializedCalled, 1) == 0)
                        {
                            errorCallback(exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }

                    if (reconnecting && !CancellationToken.IsCancellationRequested)
                    {
                        connection.State = ConnectionState.Reconnecting;

                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    IResponse response = task.Result;
                    Stream stream = response.GetResponseStream();

                    var eventSource = new EventSourceStreamReader(stream);
                    bool retry = true;

                    // When this fires close the event source
                    CancellationToken.Register(() => eventSource.Close());

                    eventSource.Opened = () =>
                    {
                        if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                        {
                            initializeCallback();
                        }

                        if (reconnecting)
                        {
                            // Change the status to connected
                            connection.State = ConnectionState.Connected;

                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Error = connection.OnError;

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.Type == EventType.Data)
                        {
                            if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            bool timedOut;
                            bool disconnected;
                            ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);

                            if (disconnected)
                            {
                                retry = false;
                            }
                        }
                    };

                    eventSource.Closed = () =>
//.........这里部分代码省略.........
开发者ID:rmarinho,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例3: PollingLoop

        private void PollingLoop(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false)
        {
            string url = connection.Url;

            // This is only necessary for the initial request where initializeCallback and errorCallback are non-null
            int callbackFired = 0;

            if (connection.MessageId == null)
            {
                url += "connect";
            }
            else if (raiseReconnect)
            {
                url += "reconnect";

                if (!connection.ChangeState(ConnectionState.Connected, ConnectionState.Reconnecting))
                {
                    return;
                }
            }

            url += GetReceiveQueryString(connection, data);

            #if NET35
            Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "LP: {0}", (object)url));
            #else
            Debug.WriteLine("LP: {0}", (object)url);
            #endif

            _httpClient.PostAsync(url, PrepareRequest(connection)).ContinueWith(task =>
            {
                // Clear the pending request
                connection.Items.Remove(HttpRequestKey);

                bool shouldRaiseReconnect = false;
                bool disconnectedReceived = false;

                try
                {
                    if (!task.IsFaulted)
                    {
                        if (raiseReconnect)
                        {
                            // If the timeout for the reconnect hasn't fired as yet just fire the
                            // event here before any incoming messages are processed
                            FireReconnected(connection);
                        }

                        // Get the response
                        var raw = task.Result.ReadAsString();

            #if NET35
                        Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "LP Receive: {0}", (object)raw));
            #else
                        Debug.WriteLine("LP Receive: {0}", (object)raw);
            #endif

                        ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
                    }
                }
                finally
                {
                    if (disconnectedReceived)
                    {
                        connection.Stop();
                    }
                    else
                    {
                        bool requestAborted = false;

                        if (task.IsFaulted)
                        {
                            // Raise the reconnect event if we successfully reconnect after failing
                            shouldRaiseReconnect = true;

                            // Get the underlying exception
                            Exception exception = task.Exception.Unwrap();

                            // If the error callback isn't null then raise it and don't continue polling
                            if (errorCallback != null &&
                                Interlocked.Exchange(ref callbackFired, 1) == 0)
                            {
                                // Call the callback
                                errorCallback(exception);
                            }
                            else
                            {
                                // Figure out if the request was aborted
                                requestAborted = ExceptionHelper.IsRequestAborted(exception);

                                // Sometimes a connection might have been closed by the server before we get to write anything
                                // so just try again and don't raise OnError.
                                if (!requestAborted && !(exception is IOException))
                                {
                                    // Raise on error
                                    connection.OnError(exception);

                                    // If the connection is still active after raising the error event wait for 2 seconds
                                    // before polling again so we aren't hammering the server
                                    TaskAsyncHelper.Delay(_errorDelay).Then(() =>
//.........这里部分代码省略.........
开发者ID:RodH257,项目名称:SignalR,代码行数:101,代码来源:LongPollingTransport.cs

示例4: OpenConnection

        private void OpenConnection(IConnection connection,
                                    string data,
                                    CancellationToken disconnectToken,
                                    Action initializeCallback,
                                    Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;
            var callbackInvoker = new ThreadSafeInvoker();
            var requestDisposer = new Disposer();

            var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);

            connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);

            HttpClient.Get(url, req =>
            {
                _request = req;
                connection.PrepareRequest(_request);

                _request.Accept = "text/event-stream";
            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Exception exception = task.Exception.Unwrap();
                    if (!ExceptionHelper.IsRequestAborted(exception))
                    {
                        if (errorCallback != null)
                        {
                            callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);

                            Reconnect(connection, data, disconnectToken);
                        }
                    }
                    requestDisposer.Dispose();
                }
                else
                {
                    var response = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    bool retry = true;

                    var esCancellationRegistration = disconnectToken.SafeRegister(state =>
                    {
                        retry = false;

                        ((IRequest)state).Abort();
                    },
                    _request);

                    eventSource.Opened = () =>
                    {
                        // If we're not reconnecting, then we're starting the transport for the first time. Trigger callback only on first start.
                        if (!reconnecting)
                        {
                            callbackInvoker.Invoke(initializeCallback);
                        }
                        else if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data)
                        {
                            if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            bool timedOut;
                            bool disconnected;
                            TransportHelper.ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);

                            if (disconnected)
                            {
                                retry = false;
                                connection.Disconnect();
                            }
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception);
//.........这里部分代码省略.........
开发者ID:armandoramirezdino,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例5: Reconnect

        // internal for testing
        internal async Task Reconnect(IConnection connection, string connectionData)
        {
            var reconnectUrl = UrlBuilder.BuildReconnect(connection, Name, connectionData);

            while (TransportHelper.VerifyLastActive(connection) && connection.EnsureReconnecting() && !_disconnectToken.IsCancellationRequested)
            {
                try
                {
                    await StartWebSocket(connection, reconnectUrl);

                    if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                    {
                        connection.OnReconnected();
                    }

                    break;
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    connection.OnError(ex);
                }

                await Task.Delay(ReconnectDelay);
            }
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:30,代码来源:WebSocketTransport.cs

示例6: OpenConnection

        internal void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, bool reconnecting)
        {
            // If we're reconnecting add /connect to the url
            var url = reconnecting
                ? UrlBuilder.BuildReconnect(connection, Name, data)
                : UrlBuilder.BuildConnect(connection, Name, data);

            connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);

            var getTask = HttpClient.Get(url, req =>
            {
                _request = req;
                _request.Accept = "text/event-stream";

                connection.PrepareRequest(_request);

            }, isLongRunning: true);

            var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
            {
                _stop = true;

                // This will no-op if the request is already finished.
                ((IRequest)state).Abort();
            }, _request);
            
            getTask.ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    var exception = task.IsCanceled
                        ? new OperationCanceledException(Resources.Error_TaskCancelledException)
                        : task.Exception.Unwrap(); 

                    if (!reconnecting)
                    {
                        TransportFailed(exception);
                    }
                    else if (!_stop)
                    {
                        // Only raise the error event if we failed to reconnect
                        connection.OnError(exception);

                        Reconnect(connection, data, disconnectToken);
                    }

                    requestCancellationRegistration.Dispose();
                }
                else
                {
                    // If the disconnect token is canceled the response to the task doesn't matter.
                    if (disconnectToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var response = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    eventSource.Opened = () =>
                    {
                        // This will noop if we're not in the reconnecting state
                        if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data &&
                            !sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                        {
                            ProcessResponse(connection, sseEvent.Data);
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            if (!ExceptionHelper.IsRequestAborted(exception))
                            {
                                // Don't raise exceptions if the request was aborted (connection was stopped).
                                connection.OnError(exception);
                            }
                        }

                        requestCancellationRegistration.Dispose();
                        response.Dispose();

                        if (_stop)
                        {
                            AbortHandler.CompleteAbort();
                        }
                        else if (AbortHandler.TryCompleteAbort())
//.........这里部分代码省略.........
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例7: PollingSetup

        private void PollingSetup(IConnection connection,
                                  string data,
                                  CancellationToken disconnectToken,
                                  PollingRequestHandler requestHandler,
                                  Action onInitialized)
        {
            // reconnectInvoker is created new on each poll
            var reconnectInvoker = new ThreadSafeInvoker();

            var disconnectRegistration = disconnectToken.SafeRegister(state =>
            {
                reconnectInvoker.Invoke();
                requestHandler.Stop();
            }, null);

            requestHandler.ResolveUrl = () =>
            {
                var url = connection.Url;

                if (connection.MessageId == null)
                {
                    url += "connect";
                    connection.Trace(TraceLevels.Events, "LP Connect: {0}", url);
                }
                else if (IsReconnecting(connection))
                {
                    url += "reconnect";
                    connection.Trace(TraceLevels.Events, "LP Reconnect: {0}", url);
                }
                else
                {
                    url += "poll";
                    connection.Trace(TraceLevels.Events, "LP Poll: {0}", url);
                }

                url += GetReceiveQueryString(connection, data);

                return url;
            };

            requestHandler.PrepareRequest += req =>
            {
                connection.PrepareRequest(req);
            };

            requestHandler.OnMessage += message =>
            {
                var shouldReconnect = false;
                var disconnectedReceived = false;

                connection.Trace(TraceLevels.Messages, "LP: OnMessage({0})", message);

                TransportHelper.ProcessResponse(connection,
                                                message,
                                                out shouldReconnect,
                                                out disconnectedReceived,
                                                onInitialized);

                if (IsReconnecting(connection))
                {
                    // If the timeout for the reconnect hasn't fired as yet just fire the 
                    // event here before any incoming messages are processed
                    TryReconnect(connection, reconnectInvoker);
                }

                if (shouldReconnect)
                {
                    // Transition into reconnecting state
                    connection.EnsureReconnecting();
                }

                if (disconnectedReceived)
                {
                    connection.Disconnect();
                }
            };

            requestHandler.OnError += exception =>
            {
                reconnectInvoker.Invoke();

                // Transition into reconnecting state
                connection.EnsureReconnecting();

                // Sometimes a connection might have been closed by the server before we get to write anything
                // so just try again and raise OnError.
                if (!ExceptionHelper.IsRequestAborted(exception) && !(exception is IOException))
                {
                    connection.OnError(exception);
                }
                else
                {
                    requestHandler.Stop();
                }
            };

            requestHandler.OnPolling += () =>
            {
                // Capture the cleanup within a closure so it can persist through multiple requests
                TryDelayedReconnect(connection, reconnectInvoker);
//.........这里部分代码省略.........
开发者ID:fszlin,项目名称:Nivot.SignalR.Client.Net35,代码行数:101,代码来源:LongPollingTransport.cs

示例8: MessageReceived

        internal void MessageReceived(IWebSocketResponse webSocketResponse, IConnection connection)
        {
            string response;

            try
            {
                response = ReadMessage(webSocketResponse);
            }
            catch (Exception ex)
            {
                connection.OnError(ex);

                var webSocket = _webSocket;
                if (webSocket != null)
                {
                    webSocket.Close(SuccessCloseStatus, ex.Message);
                }

                return;
            }

            connection.Trace(TraceLevels.Messages, "WS: OnMessage({0})", response);

            ProcessResponse(connection, response);
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:25,代码来源:WebSocketTransport.cs

示例9: OpenConnection

        private void OpenConnection(IConnection connection,
            string data,
            Action initializeCallback,
            Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool _reconnecting = initializeCallback == null;
            string _url = (_reconnecting ? connection.Url : connection.Url + "connect");
            Action<IRequest> _prepareRequest = PrepareRequest(connection);
            EventSignal<IResponse> _signal;

            if (shouldUsePost(connection))
            {
                _url += GetReceiveQueryString(connection, data);
                //Debug.WriteLine("ServerSentEventsTransport: POST {0}", _url);

                _signal = m_httpClient.PostAsync(
                    _url,
                    request =>
                    {
                        _prepareRequest(request);
                        request.Accept = "text/event-stream";
                    },
                    new Dictionary<string, string> {
                    {
                        "groups", GetSerializedGroups(connection) }
                    });
            }
            else
            {
                _url += GetReceiveQueryStringWithGroups(connection, data);
                //Debug.WriteLine("ServerSentEventsTransport: GET {0}", _url);

                _signal = m_httpClient.GetAsync(
                    _url,
                    request =>
                    {
                        _prepareRequest(request);
                        request.Accept = "text/event-stream";
                    });
            }

            _signal.Finished += (sender, e) =>
            {
                if (e.Result.IsFaulted)
                {
                    Exception _exception = e.Result.Exception.GetBaseException();

                    if (!HttpBasedTransport.IsRequestAborted(_exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref m_initializedCalled, 1) == 0)
                            errorCallback(_exception);
                        else if (_reconnecting)
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(_exception);
                    }

                    if (_reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    IResponse _response = e.Result;
                    Stream _stream = _response.GetResponseStream();
                    AsyncStreamReader _reader = new AsyncStreamReader(
                        _stream,
                        connection,
                        () =>
                        {
                            if (Interlocked.CompareExchange(ref m_initializedCalled, 1, 0) == 0)
                                initializeCallback();
                        },
                        () =>
                        {
                            _response.Close();
                            Reconnect(connection, data);
                        });

                    if (_reconnecting)
                        // Raise the reconnect event if the connection comes back up
                        connection.OnReconnected();

                    _reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[m_readerKey] = _reader;
                }
            };

            if (initializeCallback != null)
            {
                int _tryed = 0;
                while (true)
                {
//.........这里部分代码省略.........
开发者ID:PlayFab,项目名称:PlayFab-Samples,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例10: ProcessResponse

        // virtual to allow mocking
        protected internal virtual bool ProcessResponse(IConnection connection, string response)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            if (_initializationHandler == null)
            {
                throw new InvalidOperationException(Resources.Error_ProcessResponseBeforeStart);
            }

            connection.MarkLastMessage();

            if (String.IsNullOrEmpty(response))
            {
                return false;
            }

            var shouldReconnect = false;

            try
            {
                var result = connection.JsonDeserializeObject<JObject>(response);

                if (!result.HasValues)
                {
                    return false;
                }

                if (result["I"] != null)
                {
                    connection.OnReceived(result);
                    return false;
                }

                shouldReconnect = (int?)result["T"] == 1;

                var groupsToken = result["G"];
                if (groupsToken != null)
                {
                    connection.GroupsToken = (string)groupsToken;
                }

                var messages = result["M"] as JArray;
                if (messages != null)
                {
                    connection.MessageId = (string)result["C"];

                    foreach (JToken message in (IEnumerable<JToken>)messages)
                    {
                        connection.OnReceived(message);
                    }

                    if ((int?)result["S"] == 1)
                    {
                        _initializationHandler.InitReceived();
                    }
                }
            }
            catch (Exception ex)
            {
                connection.OnError(ex);
            }

            return shouldReconnect;
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:68,代码来源:ClientTransportBase.cs

示例11: ProcessResponse

        public static void ProcessResponse(IConnection connection, string response, out bool timedOut,
            out bool disconnected)
        {
            timedOut = false;
            disconnected = false;
            Debug.WriteLine("ProcessResponse: " + response);

            if (String.IsNullOrEmpty(response))
                return;

            if (connection.MessageId == null)
                connection.MessageId = null;

            try
            {
                var result = JToken.Parse(response);
                Debug.WriteLine("ProcessResponse: result parsed");

                if (!result.HasValues)
                    return;

                timedOut = result.Value<bool>("TimedOut");
                disconnected = result.Value<bool>("Disconnect");

                if (disconnected)
                    return;

                var messages = result["M"] as JArray;

                if (messages != null)
                {
                    foreach (var message in messages)
                    {
                        try
                        {
                            Debug.WriteLine("ProcessResponse: before invoking OnReceived");
                            connection.OnReceived(message);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("ProcessResponse: exception in OnReceived event '" + ex.Message + "'.");
                            connection.OnError(ex);
                        }
                    }

                    connection.MessageId = result["C"].Value<string>();

                    var transportData = result["T"] as JObject;

                    if (transportData != null)
                    {
                        var groups = (JArray) transportData["G"];
                        if (groups != null)
                        {
                            var groupList = new List<string>();
                            foreach (var groupFromTransport in groups)
                            {
                                groupList.Add(groupFromTransport.Value<string>());
                            }
                            connection.Groups = groupList;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Failed to response: {0}", ex));
                connection.OnError(ex);
            }
        }
开发者ID:Avatarchik,项目名称:uSignalR,代码行数:70,代码来源:HttpBasedTransport.cs

示例12: PollingLoop

        private void PollingLoop(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false)
        {
            string url = connection.Url;
            var reconnectTokenSource = new CancellationTokenSource();
            int reconnectFired = 0;

            if (connection.MessageId == null)
            {
                url += "connect";
            }

            url += GetReceiveQueryString(connection, data);

            _httpClient.PostAsync(url, PrepareRequest(connection)).ContinueWith(task =>
            {
                // Clear the pending request
                connection.Items.Remove(HttpRequestKey);

                bool shouldRaiseReconnect = false;
                bool disconnectedReceived = false;

                try
                {
                    if (!task.IsFaulted)
                    {
                        if (raiseReconnect)
                        {
                            // If the timeout for the reconnect hasn't fired as yet just fire the
                            // event here before any incoming messages are processed
                            FireReconnected(connection, reconnectTokenSource, ref reconnectFired);
                        }

                        // Get the response
                        var raw = task.Result.ReadAsString();

                        ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
                    }
                }
                finally
                {
                    if (disconnectedReceived)
                    {
                        connection.Stop();
                    }
                    else
                    {
                        bool requestAborted = false;
                        bool continuePolling = true;

                        if (task.IsFaulted)
                        {
                            // Cancel the previous reconnect event
                            reconnectTokenSource.Cancel();

                            // Raise the reconnect event if we successfully reconnect after failing
                            shouldRaiseReconnect = true;

                            // Get the underlying exception
                            Exception exception = task.Exception.GetBaseException();

                            // If the error callback isn't null then raise it and don't continue polling
                            if (errorCallback != null)
                            {
                                // Raise on error
                                connection.OnError(exception);

                                // Call the callback
                                errorCallback(exception);

                                // Don't continue polling if the error is on the first request
                                continuePolling = false;
                            }
                            else
                            {
                                // Figure out if the request was aborted
                                requestAborted = IsRequestAborted(exception);

                                // Sometimes a connection might have been closed by the server before we get to write anything
                                // so just try again and don't raise OnError.
                                if (!requestAborted && !(exception is IOException))
                                {
                                    // Raise on error
                                    connection.OnError(exception);

                                    // If the connection is still active after raising the error event wait for 2 seconds
                                    // before polling again so we aren't hammering the server
                                    if (connection.IsActive)
                                    {
                                        Thread.Sleep(2000);
                                    }
                                }
                            }
                        }

                        // Only continue if the connection is still active and wasn't aborted
                        if (continuePolling && !requestAborted && connection.IsActive)
                        {
                            PollingLoop(connection, data, null, null, shouldRaiseReconnect);
                        }
                    }
//.........这里部分代码省略.........
开发者ID:rhoadsce,项目名称:SignalR,代码行数:101,代码来源:LongPollingTransport.cs

示例13: OpenConnection

        private void OpenConnection(IConnection connection, string data, bool reconnecting)
        {
            // If we're reconnecting add /connect to the url
            var url = reconnecting
                ? connection.Url
                : connection.Url + "connect";

            url += GetReceiveQueryStringWithGroups(connection, data);
            Debug.WriteLine(string.Format("SSE: GET {0}", url));

            HttpClient.Get(url, request =>
            {
                connection.PrepareRequest(request);
                request.Accept = "text/event-stream";
            }, true)
                .ContinueWith(task =>
                {
                    var response = task.Result;

                    if (response.Exception != null)
                    {
                        var exception = response.Exception.GetBaseException();

                        if (!IsRequestAborted(exception))
                        {
                            if (reconnecting)
                            {
                                // Only raise the error event if we failed to reconnect
                                connection.OnError(exception);
                            }
                        }

                        if (reconnecting)
                        {
                            // Retry
                            Reconnect(connection, data);
                        }
                    }
                    else
                    {
                        // Get the response stream and read it for messages
                        var stream = response.GetResponseStream();
                        var reader = new AsyncStreamReader(stream, connection, () =>
                        {
                            response.Close();
                            Reconnect(connection, data);
                        });

                        if (reconnecting)
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();

                        reader.StartReading();

                        // Set the reader for this connection
                        connection.Items[ReaderKey] = reader;
                    }
                });
        }
开发者ID:Avatarchik,项目名称:uSignalR,代码行数:59,代码来源:ServerSentEventsTransport.cs

示例14: ProcessResponse

        public static void ProcessResponse(IConnection connection, string response, out bool timedOut, out bool disconnected)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            timedOut = false;
            disconnected = false;

            if (String.IsNullOrEmpty(response))
            {
                return;
            }

            try
            {
                var result = JValue.Parse(response);

                if (!result.HasValues)
                {
                    return;
                }

                if (result["I"] != null)
                {
                    connection.OnReceived(result);
                    return;
                }

                timedOut = result.Value<int>("T") == 1;
                disconnected = result.Value<int>("D") == 1;

                if (disconnected)
                {
                    return;
                }

                UpdateGroups(connection, groupsToken: result["G"]);

                var messages = result["M"] as JArray;
                if (messages != null)
                {
                    foreach (JToken message in messages)
                    {
                        try
                        {
                            connection.OnReceived(message);
                        }
                        catch (Exception ex)
                        {
            #if NET35
                            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Failed to process message: {0}", ex));
            #else
                            Debug.WriteLine("Failed to process message: {0}", ex);
            #endif

                            connection.OnError(ex);
                        }
                    }

                    connection.MessageId = result["C"].Value<string>();
                }
            }
            catch (Exception ex)
            {
            #if NET35
                Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Failed to response: {0}", ex));
            #else
                Debug.WriteLine("Failed to response: {0}", ex);
            #endif
                connection.OnError(ex);
            }
        }
开发者ID:belanger-simon,项目名称:SignalR,代码行数:74,代码来源:TransportHelper.cs

示例15: OpenConnection

        private void OpenConnection(IConnection connection,
                                    string data,
                                    CancellationToken disconnectToken,
                                    Action initializeCallback,
                                    Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;
            var callbackInvoker = new ThreadSafeInvoker();
            var requestDisposer = new Disposer();
            Action initializeInvoke = () =>
            {
                callbackInvoker.Invoke(initializeCallback);
            };
            var url = connection.Url + (reconnecting ? "reconnect" : "connect") + GetReceiveQueryString(connection, data);

            connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);

            HttpClient.Get(url, req =>
            {
                _request = req;
                _request.Accept = "text/event-stream";

                connection.PrepareRequest(_request);

            }, isLongRunning: true).ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Exception exception;

                    if (task.IsCanceled)
                    {
                        exception = new OperationCanceledException(Resources.Error_TaskCancelledException);
                    }
                    else
                    {
                        exception = task.Exception.Unwrap();
                    }

                    if (errorCallback != null)
                    {
                        callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
                    }
                    else if (!_stop && reconnecting)
                    {
                        // Only raise the error event if we failed to reconnect
                        connection.OnError(exception);

                        Reconnect(connection, data, disconnectToken);
                    }
                    requestDisposer.Dispose();
                }
                else
                {
                    // If the disconnect token is canceled the response to the task doesn't matter.
                    if (disconnectToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var response = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    var esCancellationRegistration = disconnectToken.SafeRegister(state =>
                    {
                        _stop = true;

                        ((IRequest)state).Abort();
                    },
                    _request);

                    eventSource.Opened = () =>
                    {
                        // This will noop if we're not in the reconnecting state
                        if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data)
                        {
                            if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            bool shouldReconnect;
                            bool disconnected;
                            TransportHelper.ProcessResponse(connection, sseEvent.Data, out shouldReconnect, out disconnected, initializeInvoke);

                            if (disconnected)
                            {
                                _stop = true;
//.........这里部分代码省略.........
开发者ID:fszlin,项目名称:Nivot.SignalR.Client.Net35,代码行数:101,代码来源:ServerSentEventsTransport.cs


注:本文中的IConnection.OnError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。