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


C# IConnection.PrepareRequest方法代码示例

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


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

示例1: 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

示例2: StartWebSocket

        private async Task StartWebSocket(IConnection connection, string url)
        {
            var uri = UrlBuilder.ConvertToWebSocketUri(url);
            connection.Trace(TraceLevels.Events, "WS Connecting to: {0}", uri);

            if (_webSocket == null)
            {
                var webSocket = new MessageWebSocket();
                webSocket.Control.MessageType = SocketMessageType.Utf8;
                webSocket.Closed += WebsocketClosed;
                webSocket.MessageReceived += MessageReceived;
                connection.PrepareRequest(new WebSocketRequest(webSocket));
                await OpenWebSocket(webSocket, uri);
                _webSocket = webSocket;
            }
         }
开发者ID:kietnha,项目名称:SignalR,代码行数:16,代码来源:WebSocketTransport.cs

示例3: 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

示例4: 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

示例5: Poll

        private void Poll(IConnection connection, string connectionData)
        {
            // This is to ensure that we do not accidently fire off another poll after being told to stop
            lock (_stopLock)
            {
                // Only poll if we're running
                if (_running == 0)
                {
                    return;
                }

                // A url is required
                var url = ResolveUrl(connection, connectionData);

                HttpClient.Post(url, request =>
                {
                    connection.PrepareRequest(request);
                    _currentRequest = request;

                    // This is called just prior to posting the request to ensure that any in-flight polling request
                    // is always executed before an OnAfterPoll
                    TryDelayedReconnect(connection, _reconnectInvoker);
                }, isLongRunning: true)
                .ContinueWith(task =>
                {
                    var next = TaskAsyncHelper.Empty;
                    Exception exception = null;

                    if (task.IsFaulted || task.IsCanceled)
                    {
                        exception = task.IsCanceled
                            ? new OperationCanceledException(Resources.Error_TaskCancelledException)
                            : task.Exception.Unwrap();

                        OnError(connection, exception);
                    }
                    else
                    {
                        try
                        {
                            next = task.Result.ReadAsString(readBuffer => OnChunk(connection, readBuffer))
                                .Then(raw => OnMessage(connection, raw));
                        }
                        catch (Exception ex)
                        {
                            exception = ex;

                            OnError(connection, exception);
                        }
                    }

                    next.Finally(
                        state => OnAfterPoll((Exception) state).Then(() => Poll(connection, connectionData)),
                        exception);
                });
            }
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:57,代码来源:LongPollingTransport.cs

示例6: PollingLoop

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

            IRequest request = null;
            var reconnectInvoker = new ThreadSafeInvoker();
            var callbackInvoker = new ThreadSafeInvoker();
            var requestDisposer = new Disposer();

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

                // FIX: Race if the connection is stopped and completely restarted between checking the token and calling
                //      connection.EnsureReconnecting()
                if (disconnectToken.IsCancellationRequested || !connection.EnsureReconnecting())
                {
                    return;
                }
            }

            url += GetReceiveQueryString(connection, data);

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

            HttpClient.Post(url, req =>
            {
                request = req;
                connection.PrepareRequest(request);
            }).ContinueWith(task =>
            {
                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
                            reconnectInvoker.Invoke((conn) => FireReconnected(conn), connection);
                        }

                        if (initializeCallback != null)
                        {
                            // If the timeout for connect hasn't fired as yet then just fire
                            // the event before any incoming messages are processed
                            callbackInvoker.Invoke(initializeCallback);
                        }

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

            #if NET35
                        Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "LP Receive: {0}", (object)raw));
            #else
                        Debug.WriteLine("LP Receive: {0}", (object)raw);
            #endif
                        TransportHelper.ProcessResponse(connection,
                                                        raw,
                                                        out shouldRaiseReconnect,
                                                        out disconnectedReceived);
                    }
                }
                finally
                {
                    if (disconnectedReceived)
                    {
                        connection.Disconnect();
                    }
                    else
                    {
                        bool requestAborted = false;

                        if (task.IsFaulted)
                        {
                            reconnectInvoker.Invoke();

                            // 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
//.........这里部分代码省略.........
开发者ID:stirno,项目名称:SignalR,代码行数:101,代码来源:LongPollingTransport.cs

示例7: 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);
            IRequest request = null;

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

            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
                {
                    IResponse response = task.Result;
                    Stream stream = response.GetResponseStream();

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

                    var esCancellationRegistration = disconnectToken.SafeRegister(es =>
                    {
                        retry = false;
                        es.Close();
                    }, eventSource);

                    eventSource.Opened = () =>
                    {
                        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 =>
                    {
                        bool isRequestAborted = false;

                        if (exception != null)
//.........这里部分代码省略.........
开发者ID:stirno,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例8: 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

示例9: 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


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