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


C# IConnection.Disconnect方法代码示例

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


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

示例1: RunClientSubscriber

        private void RunClientSubscriber(IConnection<SimpleMessage<int>, int> connection, IConnectionStubListener<SimpleMessage<int>, int> listener, ushort port)
        {
            listener.BindTo(new IPEndPoint(IPAddress.Any, port));
            var listenerTask = Task.Run(() => RunListenerSubscriber(listener));
            var ready = false;
            connection.Subscribe(0, (message, size) => ready = true);
            connection.Subscribe(1, (message, size) => TextMessageHandler("Client", message, size));
            connection.Connect(new IPEndPoint(IPAddress.Loopback, port));
            while (!ready)
                Thread.CurrentThread.Join(10);

            const int messages = 500;
            Console.WriteLine(@"Sending {0} messages with random data", 5);
            var rnd = new Random();
            for (var i = 0; i < messages; ++i)
            {
                var data = new byte[rnd.Next(16, 256)];
                rnd.NextBytes(data);
                connection.Send(new SimpleMessage<int>(1, Encoding.ASCII.GetBytes(Convert.ToBase64String(data))));
            }
            Console.WriteLine(@"Client: Done, sending exit message");
            connection.Send(new SimpleMessage<int>(2));
            connection.Disconnect();
            Console.WriteLine(@"Waiting for listener thread to exit");
            listenerTask.Wait();
            Console.WriteLine(@"Listener thread has exited");
            Console.WriteLine();
            Console.WriteLine(@"Press any key to exit");
            Console.ReadKey();
        }
开发者ID:Melamew,项目名称:iLynx.Common,代码行数:30,代码来源:TcpConnectionTests.cs

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

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

示例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);
            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

示例5: OpenConnection


//.........这里部分代码省略.........
                    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;
                                connection.Disconnect();
                            }
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception);

                            if (!isRequestAborted)
                            {
                                // Don't raise exceptions if the request was aborted (connection was stopped).
                                connection.OnError(exception);
                            }
                        }

                        requestDisposer.Dispose();
                        esCancellationRegistration.Dispose();
                        response.Dispose();

                        if (_stop)
                        {
                            AbortHandler.CompleteAbort();
                        }
                        else if (AbortHandler.TryCompleteAbort())
                        {
                            // Abort() was called, so don't reconnect
                        }
                        else
                        {
                            Reconnect(connection, data, disconnectToken);
                        }
                    };

                    eventSource.Start();
                }
            });

            var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
            {
                if (state != null)
                {
                    // This will no-op if the request is already finished.
                    ((IRequest)state).Abort();
                }

                if (errorCallback != null)
                {
                    callbackInvoker.Invoke((cb, token) =>
                    {
#if !NET35
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token));
#else
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled));
#endif
                    }, errorCallback, disconnectToken);
                }
            }, _request);

            requestDisposer.Set(requestCancellationRegistration);
        }
开发者ID:fszlin,项目名称:Nivot.SignalR.Client.Net35,代码行数:101,代码来源:ServerSentEventsTransport.cs

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

示例7: SessionHandler

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="cancellationToken"></param>
        public void SessionHandler(IConnection connection, CancellationTokenSource cancellationToken)
        {
            var mres = new ManualResetEventSlim(false);
            try
            {
                _logger.Info("Session Started");

                _connections.Add(connection);

                _transport.ReceiveAsync(connection, OnIncomingMessageReceived);

                mres.Wait(cancellationToken.Token);
                
                if (connection.Exception != null)
                    throw connection.Exception;
            }
            catch (OperationCanceledException)
            {
                _logger.Info("Session Cancelled!");
            }
            catch (Exception ex)
            {
                _logger.Error("Session Exception", ex);

                throw ex;
            }
            finally
            {
                _connections.Remove(connection);

                connection.Disconnect();
                
                _sessionCancelationTokens.Remove(cancellationToken);
                
                _logger.Info("Session Ended");
            }
        }
开发者ID:dinsight,项目名称:PigeonMQ,代码行数:42,代码来源:PigeonServer.cs

示例8: CloseConnection

        /// <summary>
        /// Closes the specified connection
        /// </summary>
        /// <param name="connection">Connection that is to be closed.</param>
        public void CloseConnection(IConnection connection)
        {
            if (connection is Connection)
            {
                var conn = (Connection)connection;
                conn.DataSent -= EventHandlerDataSent;
                conn.DataReceived -= EventHandlerDataReceived;
                conn.ClientDisconnected -= EventHandlerClientDisconnected;
            }

            connection.Disconnect();
            lock (LockObject)
            {
                connections.Remove(connection);
                if (ClientDisconnected != null)
                {
                    ClientDisconnected(this, new ConnectionArgs(connection));
                }
            }
        }
开发者ID:Hobbitron,项目名称:WheelMUD,代码行数:24,代码来源:BaseServer.cs

示例9: Disconnect

        public void Disconnect(IConnection connection)
        {
            connection.MessageReceived -= this.Server_MessageReceived;
            connection.Disconnected -= this.Server_Disconnected;

            if(connection.IsConnected)
                connection.Disconnect();

            NetworkPlayer player = this.players.GetPlayer(connection);

            PlayerUpdateMessage updatemsg = new PlayerUpdateMessage();
            updatemsg.Action = PlayerUpdateAction.Remove;
            updatemsg.NetworkID = player.NetworkID;

            lock(this.players.PlayerLock)
            {
                foreach(var nplayer in this.players.PlayerRanges[player.NetworkID])
                    nplayer.Connection.Send (updatemsg);
            }

            this.players.RemovePlayer (connection);

            this.SaveCharacter(player.Character);

            // fire logged out event
            var handler = this.UserLoggedOut;
            if(handler != null)
                handler (this, new UserEventArgs (player));
        }
开发者ID:heyitsanewb,项目名称:PokeWorld-Online,代码行数:29,代码来源:ValkyrieGameServer.cs

示例10: MyNick

 public MyNick(IConnection con, string raw)
     : base(con, raw)
 {
     int pos;
     if ((pos = raw.IndexOf(" ")) != -1) {
         pos++;
         info = new UserInfo();
         info.DisplayName = raw.Substring(pos);
         valid = true;
         // TODO : Check against Usernames in hub should be done here.
         return;
     }
     con.Disconnect("Handshake was failing.");
 }
开发者ID:BGCX261,项目名称:zpoc3-svn-to-git,代码行数:14,代码来源:transferzpocmessages.cs


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