예제 #1
0
파일: NoModem.cs 프로젝트: whble/crterm
 public void Disconnect()
 {
     if (Transport != null)
     {
         Transport.Close();
     }
 }
예제 #2
0
 public override void Close()
 {
     if (Transport != null && Transport.IsOpen)
     {
         Transport.Close();
     }
 }
예제 #3
0
        private void HandleSessionDisconnect(string msg)
        {
            Connected = false;

            Events.Trigger("disconnect", new ErrorResponse(msg));

            Transport.Close();
        }
예제 #4
0
        /// <summary>
        /// Closes this Socket.IO connection.
        /// </summary>
        void IManager.Close(bool removeSockets)
        {
            if (State == States.Closed || closing)
            {
                return;
            }
            closing = true;

            HTTPManager.Logger.Information("SocketManager", "Closing");

            HTTPManager.Heartbeats.Unsubscribe(this);

            // Disconnect the sockets. The Disconnect function will call the Remove function to remove it from the Sockets list.
            if (removeSockets)
            {
                while (Sockets.Count > 0)
                {
                    (Sockets[Sockets.Count - 1] as ISocket).Disconnect(removeSockets);
                }
            }
            else
            {
                for (int i = 0; i < Sockets.Count; ++i)
                {
                    (Sockets[i] as ISocket).Disconnect(removeSockets);
                }
            }

            // Set to Closed after Socket's Disconnect. This way we can send the disconnect events to the server.
            State = States.Closed;

            LastHeartbeat = DateTime.MinValue;

            if (OfflinePackets != null)
            {
                OfflinePackets.Clear();
            }

            // Remove the references from the dictionary too.
            if (removeSockets)
            {
                Namespaces.Clear();
            }

            if (Handshake != null)
            {
                Handshake.Abort();
            }
            Handshake = null;

            if (Transport != null)
            {
                Transport.Close();
            }
            Transport = null;

            closing = false;
        }
예제 #5
0
 public void Disconnect()
 {
     if (Modem != null)
     {
         Modem.Disconnect();
     }
     if (Transport != null)
     {
         Transport.Close();
     }
 }
예제 #6
0
 public void Disconnect()
 {
     Token = null;
     if (Transport.Connected)
     {
         CBye();
     }
     if (Transport != null)
     {
         Transport.Close();
     }
     Transport = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     Status    = ConnectionStatus.NotConnected;
     App.ViewModel.AddDebugLog("!Disconnected");
 }
예제 #7
0
        public void DestroyTransport(bool suppressClosedEvent)
        {
            if (Logger.IsDebug)
            {
                Logger.Debug("Destroying transport");
            }

            if (Transport == null)
            {
                return;
            }

            Transport.Close(suppressClosedEvent);
            Transport.Listener = null;
            Transport          = null;
        }
예제 #8
0
 void IManager.Close(bool removeSockets)
 {
     if (State != States.Closed && !closing)
     {
         closing = true;
         HTTPManager.Logger.Information("SocketManager", "Closing");
         HTTPManager.Heartbeats.Unsubscribe(this);
         if (removeSockets)
         {
             while (Sockets.Count > 0)
             {
                 ((ISocket)Sockets[Sockets.Count - 1]).Disconnect(removeSockets);
             }
         }
         else
         {
             for (int i = 0; i < Sockets.Count; i++)
             {
                 ((ISocket)Sockets[i]).Disconnect(removeSockets);
             }
         }
         State         = States.Closed;
         LastHeartbeat = DateTime.MinValue;
         if (OfflinePackets != null)
         {
             OfflinePackets.Clear();
         }
         if (removeSockets)
         {
             Namespaces.Clear();
         }
         if (Handshake != null)
         {
             Handshake.Abort();
         }
         Handshake = null;
         if (Transport != null)
         {
             Transport.Close();
         }
         Transport = null;
         closing   = false;
     }
 }
예제 #9
0
        public async Task Disconnect()
        {
            var request = new WCSessionUpdate(new WCSessionData()
            {
                approved  = false,
                chainId   = null,
                accounts  = null,
                networkId = null
            });

            await SendRequest(request);

            await Transport.Close();

            if (OnDisconnect != null)
            {
                OnDisconnect(this, this);
            }
        }
        public bool Close()
        {
            try
            {
                bool close = Transport.Close();

                if (close && OnClose != null)
                {
                    OnClose(this);
                }

                return(close);
            }
            catch (Exception e)
            {
                if (OnError != null)
                {
                    OnError(this, e);
                }

                return(false);
            }
        }
예제 #11
0
 /// <summary>
 /// Closes the instance and releases resources.
 /// </summary>
 public void Close()
 {
     _isRunning = false;
     Transport.Close();
 }
예제 #12
0
 public void Close()
 {
     Transport.Close();
 }
예제 #13
0
 /// <summary>
 /// Closes the connection to the PClient.
 /// Doing this for every single evaluation can be very bad for performance.
 /// </summary>
 public static void Close()
 {
     Socket.Close();
     Transport.Close();
 }
예제 #14
0
        public void OnAuthUpdated(object sender, AblyAuthUpdatedEventArgs args)
        {
            if (State.State == ConnectionState.Connected)
            {
                /* (RTC8a) If the connection is in the CONNECTED state and
                 * auth.authorize is called or Ably requests a re-authentication
                 * (see RTN22), the client must obtain a new token, then send an
                 * AUTH ProtocolMessage to Ably with an auth attribute
                 * containing an AuthDetails object with the token string. */
                try
                {
                    /* (RTC8a3) The authorize call should be indicated as completed
                    * with the new token or error only once realtime has responded
                    * to the AUTH with either a CONNECTED or ERROR respectively. */

                    // an ERROR protocol message will fail the connection
                    void OnFailed(object o, ConnectionStateChange change)
                    {
                        if (change.Current == ConnectionState.Failed)
                        {
                            Connection.InternalStateChanged -= OnFailed;
                            Connection.InternalStateChanged -= OnConnected;
                            args.CompleteAuthorization(false);
                        }
                    }

                    void OnConnected(object o, ConnectionStateChange change)
                    {
                        if (change.Current == ConnectionState.Connected)
                        {
                            Connection.InternalStateChanged -= OnFailed;
                            Connection.InternalStateChanged -= OnConnected;
                            args.CompleteAuthorization(true);
                        }
                    }

                    Connection.InternalStateChanged += OnFailed;
                    Connection.InternalStateChanged += OnConnected;

                    var msg = new ProtocolMessage(ProtocolMessage.MessageAction.Auth)
                    {
                        Auth = new AuthDetails {
                            AccessToken = args.Token.Token
                        }
                    };

                    Send(msg);
                }
                catch (AblyException e)
                {
                    Logger.Warning("OnAuthUpdated: closing transport after send failure");
                    Logger.Debug(e.Message);
                    Transport?.Close();
                }
            }
            else
            {
                args.CompletedTask.TrySetResult(true);
                Connect();
            }
        }
예제 #15
0
        /// <summary>
        /// Called from the HTTPManager's OnUpdate function every frame. It's main function is to send out heartbeat messages.
        /// </summary>
        void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
        {
            switch (State)
            {
            case States.Paused:
                // To ensure no messages are lost, the upgrade packet will only be sent once all the buffers of the existing transport are flushed and the transport is considered paused.
                if (!Transport.IsRequestInProgress &&
                    !Transport.IsPollingInProgress)
                {
                    State = States.Open;

                    // Close the current transport
                    Transport.Close();

                    // and switch to the newly upgraded one
                    Transport          = UpgradingTransport;
                    UpgradingTransport = null;

                    // We will send an Upgrade("5") packet.
                    Transport.Send(this.Parser.CreateOutgoing(TransportEventTypes.Upgrade, null));

                    goto case States.Open;
                }
                break;

            case States.Opening:
                if (DateTime.UtcNow - ConnectionStarted >= Options.Timeout)
                {
                    (this as IManager).EmitError("Connection timed out!");
                    (this as IManager).EmitEvent("connect_error");
                    (this as IManager).EmitEvent("connect_timeout");
                    (this as IManager).TryToReconnect();
                }

                break;

            case States.Reconnecting:
                if (ReconnectAt != DateTime.MinValue && DateTime.UtcNow >= ReconnectAt)
                {
                    (this as IManager).EmitEvent("reconnect_attempt");
                    (this as IManager).EmitEvent("reconnecting");

                    Open();
                }
                break;

            case States.Open:
                ITransport trans = null;

                // Select transport to use
                if (Transport != null && Transport.State == TransportStates.Open)
                {
                    trans = Transport;
                }

                // not yet open?
                if (trans == null || trans.State != TransportStates.Open)
                {
                    return;
                }

                // Start to poll the server for events
                trans.Poll();

                // Start to send out unsent packets
                SendOfflinePackets();

                // First time we reached this point. Set the LastHeartbeat to the current time, 'cause we are just opened.
                if (LastHeartbeat == DateTime.MinValue)
                {
                    LastHeartbeat    = DateTime.UtcNow;
                    lastPingReceived = DateTime.UtcNow;
                    return;
                }

                if (DateTime.UtcNow - lastPingReceived > TimeSpan.FromMilliseconds(Handshake.PingInterval + Handshake.PingTimeout))
                {
                    (this as IManager).TryToReconnect();
                }

                break;     // case States.Open:
            }
        }
예제 #16
0
        internal async Task OnAuthUpdated(TokenDetails tokenDetails, bool wait)
        {
            if (Connection.State != ConnectionState.Connected)
            {
                ExecuteCommand(Connect());
                return;
            }

            try
            {
                var msg = new ProtocolMessage(ProtocolMessage.MessageAction.Auth)
                {
                    Auth = new AuthDetails
                    {
                        AccessToken = tokenDetails.Token,
                    },
                };

                Send(msg);
            }
            catch (AblyException e)
            {
                Logger.Warning("OnAuthUpdated: closing transport after send failure");
                Logger.Debug(e.Message);
                Transport?.Close();
            }

            if (wait)
            {
                var waiter = new ConnectionChangeAwaiter(Connection);

                try
                {
                    while (true)
                    {
                        var(success, newState) = await waiter.Wait(Defaults.DefaultRealtimeTimeout);

                        if (success == false)
                        {
                            throw new AblyException(
                                      new ErrorInfo(
                                          $"Connection state didn't change after Auth updated within {Defaults.DefaultRealtimeTimeout}",
                                          40140));
                        }

                        switch (newState)
                        {
                        case ConnectionState.Connected:
                            Logger.Debug("onAuthUpdated: Successfully connected");
                            return;

                        case ConnectionState.Connecting:
                        case ConnectionState.Disconnected:
                            continue;

                        default:     // if it's one of the failed states
                            Logger.Debug("onAuthUpdated: Failed to reconnect");
                            throw new AblyException(Connection.ErrorReason);
                        }
                    }
                }
                catch (AblyException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    Logger.Error("Error in AuthUpdated handler", e);
                    throw new AblyException(
                              new ErrorInfo("Error while waiting for connection to update after updating Auth"), e);
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Called from the HTTPManager's OnUpdate function every frame. It's main function is to send out heartbeat messages.
        /// </summary>
        void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
        {
            switch (State)
            {
            case States.Paused:
                // To ensure no messages are lost, the upgrade packet will only be sent once all the buffers of the existing transport are flushed and the transport is considered paused.
                if (!Transport.IsRequestInProgress &&
                    !Transport.IsPollingInProgress)
                {
                    State = States.Open;

                    // Close the current transport
                    Transport.Close();

                    // and switch to the newly upgraded one
                    Transport          = UpgradingTransport;
                    UpgradingTransport = null;

                    // We will send an Upgrade("5") packet.
                    Transport.Send(new Packet(TransportEventTypes.Upgrade, SocketIOEventTypes.Unknown, "/", string.Empty));

                    goto case States.Open;
                }
                break;

            case States.Opening:
                if (DateTime.UtcNow - ConnectionStarted >= Options.Timeout)
                {
                    (this as IManager).EmitError(SocketIOErrors.Internal, "Connection timed out!");
                    (this as IManager).EmitEvent("connect_error");
                    (this as IManager).EmitEvent("connect_timeout");
                    (this as IManager).TryToReconnect();
                }

                break;

            case States.Reconnecting:
                if (ReconnectAt != DateTime.MinValue && DateTime.UtcNow >= ReconnectAt)
                {
                    (this as IManager).EmitEvent("reconnect_attempt");
                    (this as IManager).EmitEvent("reconnecting");

                    Open();
                }
                break;

            case States.Open:
                ITransport trans = null;

                // Select transport to use
                if (Transport != null && Transport.State == TransportStates.Open)
                {
                    trans = Transport;
                }

                // not yet open?
                if (trans == null || trans.State != TransportStates.Open)
                {
                    return;
                }

                // Start to poll the server for events
                trans.Poll();

                // Start to send out unsent packets
                SendOfflinePackets();

                // First time we reached this point. Set the LastHeartbeat to the current time, 'cause we are just opened.
                if (LastHeartbeat == DateTime.MinValue)
                {
                    LastHeartbeat = DateTime.UtcNow;
                    return;
                }

                // It's time to send out a ping event to the server
                if (DateTime.UtcNow - LastHeartbeat > Handshake.PingInterval)
                {
                    (this as IManager).SendPacket(new Packet(TransportEventTypes.Ping, SocketIOEventTypes.Unknown, "/", string.Empty));

                    LastHeartbeat = DateTime.UtcNow;
                    IsWaitingPong = true;
                }

                // No pong event received in the given time, we are disconnected.
                if (IsWaitingPong && DateTime.UtcNow - LastHeartbeat > Handshake.PingTimeout)
                {
                    IsWaitingPong = false;
                    (this as IManager).TryToReconnect();
                }

                break;     // case States.Open:
            }
        }
예제 #18
0
        private void ProcessReply(string line)
        {
            App.ViewModel.AddDebugLog(string.Format("<{0}", line));
            var pattern = "^([A-Z]+)([:][A-Z0-9_]+)?(|.+)?$";
            var match   = Regex.Match(line, pattern);

            if (match.Success)
            {
                var     command   = match.Groups[1].Value;
                var     parameter = string.IsNullOrEmpty(match.Groups[2].Value) ? null : match.Groups[2].Value.Substring(1);
                var     addict    = string.IsNullOrWhiteSpace(match.Groups[3].Value) ? null : match.Groups[3].Value.Substring(1).Trim();
                dynamic json      = string.IsNullOrEmpty(addict) ? null
                                        : JsonConvert.DeserializeObject <dynamic>(addict, new JsonSerializerSettings {
                    Error = (s, e) => { e.ErrorContext.Handled = true; }
                });
                if (json == null)
                {
                    json = JsonConvert.DeserializeObject <dynamic>("{}");
                }

                switch (command)
                {
                case "BYE":
                    Transport.Shutdown(SocketShutdown.Both);
                    Transport.Close();
                    break;

                case "G":
                    foreach (var c in (json as JArray).Cast <JValue>().Select(s => s.Value.ToString().Split('|')).ToList())
                    {
                        Do(() => { App.ViewModel.GroupsModel.AddCoordinate(c[0], Coordinate.Create(c[1])); });
                    }
                    break;

                case "GA":
                    CGroup();
                    break;

                case "GD":
                    CGroup();
                    break;

                case "GE":
                    CGroup();
                    break;

                case "GP":
                    var group = JsonConvert.DeserializeObject <Group>(addict);
                    Do(() => { App.ViewModel.GroupsModel.SetUsers(parameter, group.Users); });
                    CGpr(parameter);
                    break;

                case "GPR":
                    break;

                case "GROUP":
                    Do(() => { lock (App.ViewModel.GroupsModel.Groups) { App.ViewModel.GroupsModel.Groups = JsonConvert.DeserializeObject <List <Group> >(addict); } });
                    break;

                case "INIT":
                    if (json["error"] != null)
                    {
                        Disconnect();
                    }
                    else
                    {
                        Do(() => { App.ViewModel.TrackerId = ((JValue)json["id"]).ToObject <string>(); });
                        CMd();
                    }
                    break;

                case "MD":
                    Status = ConnectionStatus.Connected;
                    while (SendQueue.Count > 0)
                    {
                        Send(SendQueue.Dequeue());
                    }
                    Do(() => { App.ViewModel.MessageOfTheDay = addict; });
                    break;

                case "P":
                    break;

                case "PP":
                    CP();
                    break;

                case "RC":
                    break;

                case "TO":
                    Do(() => { App.ViewModel.SessionId = ((JValue)json["url"]).ToObject <string>(); });
                    break;

                case "T":
                    break;

                case "TC":
                    Do(() => { App.ViewModel.SessionId = null; });
                    break;

                default:
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    break;
                }
            }
        }