Exemple #1
0
        protected virtual void ServicePortConnState(ConnState remoteEndHasBeenClosedState)
        {
            if (BaseState.IsConnected && (dataSP == null || !dataSP.Connected))
            {
                DisposeDataSocket(false);
                SetBaseState(ConnState.ConnectionFailed, "Socket is no longer connected", true);
            }

            if (BaseState.IsConnected && (lastReadResult == ActionResultEnum.ReadRemoteEndHasBeenClosed))
            {
                try
                {
                    if (dataSP != null)
                    {
                        DisposeDataSocket();
                    }

                    SetBaseState(remoteEndHasBeenClosedState, "Socket remote end has been closed", true);
                }
                catch (System.Exception ex)
                {
                    SetBaseState(ConnState.ConnectionFailed, Fcns.CheckedFormat("Unable to close data socket while handling remote end closed: {0}", ex), true);
                }
            }
        }
Exemple #2
0
        bool ProcessLine(string line)
        {
            switch (state)
            {
            case ConnState.UserName:
                Character = CharData.Load(line, this);

                Character.Name = NormalizeName(line);
                state          = ConnState.Pass;
                break;

            case ConnState.Pass:
                if (!Character.Authenticate(line))
                {
                    SendToCharacter("Invaild password.");
                    Disconnect();
                    break;
                }
                state = ConnState.Interp;
                break;

            case ConnState.Interp:
                Interp(line);
                break;
            }

            return(true);
        }
Exemple #3
0
        public AlbumContext()
        {
            state = ConnState.Disconnected;

            // jserv = Preferences.jserv;
            // Assert.IsNotNull(jserv);
        }
Exemple #4
0
            public void antChannel_channelResponse_DataFetch(ANT_Response response)
            {
                if (curStatus == ConnState.Connected)
                {
                    //If the channel closes we need to know
                    if (response.responseID == (byte)ANT_ReferenceLibrary.ANTMessageID.RESPONSE_EVENT_0x40 &&
                        response.messageContents[1] == (byte)ANT_ReferenceLibrary.ANTMessageID.EVENT_0x01)
                    {
                        if (response.messageContents[2] == (byte)ANT_ReferenceLibrary.ANTEventID.EVENT_RX_FAIL_GO_TO_SEARCH_0x08)
                        {
                            dataSource.isInitialized = false;
                            curStatus = ConnState.DrpdToSrch;
                        }
                        else if (response.messageContents[2] == (byte)ANT_ReferenceLibrary.ANTEventID.EVENT_CHANNEL_CLOSED_0x07)
                        {
                            curStatus = ConnState.Closed;   //TODO: qc Ensure search channel is cycling, or we will never get this back
                        }
                    }
                }
                else if (curStatus == ConnState.DrpdToSrch)  //If we are in search and see a new broadcast
                {
                    if (response.responseID == (byte)ANT_Managed_Library.ANT_ReferenceLibrary.ANTMessageID.BROADCAST_DATA_0x4E)
                    {
                        curStatus = ConnState.Connected;
                    }
                }

                dataSource.handleChannelResponse(response);
            }
Exemple #5
0
    public void OnServerConnectedCallback()
    {
        Debug.Log("server connected");
        conn_state = ConnState.CONNECTED;

        lock (conn_status)
        {
            conn_status = "connected";
        }
    }
Exemple #6
0
    public void OnErrorCallbackHandler(int err)
    {
        lock (conn_status)
        {
            conn_status = string.Format("error: {0}", err);
            Debug.Log(conn_status);
        }

        conn_state = ConnState.ERROR;
    }
        public void Connection()
        {
            ConnState state = (ConnState)Settings.Default.Context["conn"];

            if (ConnState.ConnFail == state)
            {
                trayIcon.Icon = Resources.SysguardOnline;
                Settings.Default.Context.Remove("conn");
                Settings.Default.Context.Add("conn", ConnState.ConnSuccess);
            }
        }
        /// <summary>
        /// Updates the official connection status
        /// </summary>
        /// <param name="status"></param>
        private void SetStatus(ConnState status)
        {
            if (this._status != status)
            {
                this._status = status;

                //notify the event's subscribers
                var handler = this._options.StateChangedEventHandler;
                if (handler != null)
                {
                    this._stateChangedEventArgs.State = this._status;
                    handler(this._stateChangedEventArgs);
                }
            }
        }
Exemple #9
0
        private void setPeerState(Int64 peerId, ConnState state)
        {
            var prevState = GetPeerState(peerId);

            if (state == ConnState.Idle)
            {
                connState.Remove(peerId);
            }
            else
            {
                connState[peerId] = state;
            }

            trace(string.Format("{0}-main {1} to {2}", peerId, prevState, state));
        }
Exemple #10
0
    public void ConnectToServer(string strServer, int port)
    {
        if (conn_state == ConnState.CONNECTING || conn_state == ConnState.CONNECTED)
        {
            return;
        }

        network_comm.ConnectServer(strServer, port);

        conn_state = ConnState.CONNECTING;

        lock (conn_status)
        {
            conn_status = "connecting";
        }
    }
Exemple #11
0
        private void ProcessConnectInit()
        {
            this._status = ConnState.CONNECTING;

            _serverInfo = ProcessExpectedInfo();
            SendConnect();

            // .NET vs go design difference here:
            // Starting the ping timer earlier allows us
            // to assign, and thus, dispose of it if the connection
            // is disposed before the socket watchers are running.
            // Otherwise, the connection is referenced by an orphaned
            // ping timer which can create a memory leak.
            //TODO:Implement timer
            //StartPingTimer();

            LaunchReaderLoop();
        }
        protected async Task <bool> UpdateRefreshStatus(bool b)
        {
            TokenSource.Token.ThrowIfCancellationRequested();

            this.HasRefreshRequest = false;
            if (b == true)
            {
                this.ConnectionState = ConnState.CONNECTED;
                this.IsConnected     = true;
            }
            else
            {
                this.ConnectionState = ConnState.ERROR;
                this.IsConnected     = false;
            }
            this.IsActive = false;

            return(b);
        }
Exemple #13
0
        private void SendConnect()
        {
            WriteString(connectProto());
            WriteString(IC.pingProto);
            _bw.Flush();

            StreamReader sr     = new StreamReader(_br);
            string       result = sr.ReadLine();

            // If opts.verbose is set, handle +OK.
            if (_options.Verbose == true && IC.okProtoNoCRLF.Equals(result))
            {
                result = sr.ReadLine();
            }

            if (IC.pongProtoNoCRLF.Equals(result))
            {
                _status = ConnState.CONNECTED;
                return;
            }
            else
            {
                if (result == null)
                {
                    throw new FastNATSConnectionException("Connect read protocol error");
                }
                else if (result.StartsWith(IC._ERR_OP_))
                {
                    throw new FastNATSConnectionException(
                              result.Substring(IC._ERR_OP_.Length));
                }
                else
                {
                    throw new FastNATSException("Error from sendConnect(): " + result);
                }
            }
        }
        protected virtual async Task DoPeriodicWorkAsync(TimeSpan dueTime,
                                                         TimeSpan interval,
                                                         CancellationToken token)
        {
            // Initial wait time before we begin the periodic loop.
            if (dueTime > TimeSpan.Zero)
            {
                await Task.Delay(dueTime, token);
            }

            // Repeat this loop until cancelled.
            while (!token.IsCancellationRequested)
            {
                // Wait to repeat again.
                if (interval > TimeSpan.Zero)
                {
                    this.HasRefreshRequest = true;
                    this.ConnectionState   = ConnState.CONNECTING;
                    this.IsActive          = true;
                    TokenSource.Token.ThrowIfCancellationRequested();
                    // run the Action that is meant to fire when we refresh, then update the Connector Properties, then wait
                    try
                    {
                        bool b = await ConnectionAction();

                        bool b2 = await UpdateRefreshStatus(b);

                        await Task.Delay(dueTime, token);
                    }
                    catch (Exception ex)
                    {
                        var e = ex;
                        throw;
                    }
                }
            }
        }
Exemple #15
0
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var behavior = (parameter != null) ? ((parameter is PartBaseStateDenyReasonSetConverterBehavior) ? (PartBaseStateDenyReasonSetConverterBehavior)parameter : ValueContainer.CreateFromObject(parameter).GetValue <PartBaseStateDenyReasonSetConverterBehavior>(rethrow: false)) : default(PartBaseStateDenyReasonSetConverterBehavior);

            IBaseState baseState             = (value as IBaseState).MapDefaultTo(BaseState.None);
            UseState   useState              = baseState.UseState;
            ConnState  connState             = baseState.ConnState;
            bool       useStateIsBusy        = (useState == UseState.OnlineBusy || useState == UseState.AttemptOnline);
            bool       connStateIsBusy       = (connState == ConnState.Connecting);
            bool       connStateIsApplicable = (connState != ConnState.NotApplicable && connState != ConnState.Undefined);

            BaseState.ToStringSelect toStringSelect = BaseState.ToStringSelect.UseStateNoPrefix | BaseState.ToStringSelect.ConnState | ((useState == UseState.OnlineBusy) ? BaseState.ToStringSelect.ActionName : BaseState.ToStringSelect.Reason);

            switch (behavior)
            {
            case PartBaseStateDenyReasonSetConverterBehavior.IsFullyOnlineAndIdle:
                if (useStateIsBusy)
                {
                    return("Part '{0}' is not idle: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                else if (!useState.IsOnline(acceptAttemptOnline: false, acceptUninitialized: false, acceptOnlineFailure: false, acceptAttemptOnlineFailed: false))
                {
                    return("Part '{0}' is not online: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                else if (!connState.IsConnected() && connStateIsApplicable)
                {
                    return("Part '{0}' is not connected: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                break;

            case PartBaseStateDenyReasonSetConverterBehavior.IsOnlineAndIdle:
                if (useStateIsBusy)
                {
                    return("Part '{0}' is not idle: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                else if (!useState.IsOnline(acceptAttemptOnline: false, acceptUninitialized: true, acceptOnlineFailure: true, acceptAttemptOnlineFailed: false))
                {
                    return("Part '{0}' is not online: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                else if (!connState.IsConnected() && connStateIsApplicable)
                {
                    return("Part '{0}' is not connected: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                break;

            case PartBaseStateDenyReasonSetConverterBehavior.IsOnline:
                if (!useState.IsOnline(acceptAttemptOnline: true, acceptUninitialized: true, acceptOnlineFailure: true, acceptAttemptOnlineFailed: false))
                {
                    return("Part '{0}' is not online: {1}".CheckedFormat(baseState.PartID, baseState.ToString(toStringSelect)));
                }
                break;

            case PartBaseStateDenyReasonSetConverterBehavior.IsNotBusy:
                if (useStateIsBusy)
                {
                    return("Part '{0}' is not idle: {1}".CheckedFormat(baseState.PartID, baseState.ToString(BaseState.ToStringSelect.AllForPart)));
                }
                break;

            default:
                return("Invalid requested conversion beahvior [{0}]".CheckedFormat(behavior));
            }

            return(EmptyArrayFactory <string> .Instance);
        }
Exemple #16
0
 public AlbumContext State(ConnState state)
 {
     this.state = state;
     return(this);
 }
Exemple #17
0
 public OnDisconnectedHandlerArgs(ConnState state)
 {
     State = state;
 }
Exemple #18
0
        // caller must lock.
        private void sendConnect()
        {
            try
            {
                writeString(connectProto());
                bw.Write(PING_P_BYTES, 0, PING_P_BYTES_LEN);
                bw.Flush();
            }
            catch (Exception ex)
            {
                if (lastEx == null)
                    throw new NATSException("Error sending connect protocol message", ex);
            }

            string result = null;
            try
            {
                StreamReader sr = new StreamReader(br);
                result = sr.ReadLine();


                // If opts.verbose is set, handle +OK.
                if (opts.Verbose == true && IC.okProtoNoCRLF.Equals(result))
                {
                    result = sr.ReadLine();
                }

                // Do not close or dispose the stream reader; 
                // we need the underlying BufferedStream.
            }
            catch (Exception ex)
            {
                throw new NATSConnectionException("Connect read error", ex);
            }

            if (IC.pongProtoNoCRLF.Equals(result))
            {
                status = ConnState.CONNECTED;
                return;
            }
            else
            {
                if (result == null)
                {
                    throw new NATSConnectionException("Connect read protocol error");
                }
                else if (result.StartsWith(IC._ERR_OP_))
                {
                    throw new NATSConnectionException(
                        result.Substring(IC._ERR_OP_.Length));
                }
                else
                {
                    throw new NATSException("Error from sendConnect(): " + result);
                }
            }
        }
Exemple #19
0
 private void processDisconnect()
 {
     status = ConnState.DISCONNECTED;
     if (lastEx == null)
         return;
 }
Exemple #20
0
        public override void Release()
        {
            base.Release();

            State = ConnState.None;
        }
Exemple #21
0
        // Low level close call that will do correct cleanup and set
        // desired status. Also controls whether user defined callbacks
        // will be triggered. The lock should not be held entering this
        // function. This function will handle the locking manually.
        private void close(ConnState closeState, bool invokeDelegates)
        {
            lock (mu)
            {
                if (isClosed())
                {
                    status = closeState;
                    return;
                }

                status = ConnState.CLOSED;

                // Kick the routines so they fall out.
                // fch will be closed on finalizer
                kickFlusher();
            }

            lock (mu)
            {
                // Clear any queued pongs, e.g. pending flush calls.
                clearPendingFlushCalls();

                stopPingTimer();

                // Close sync subscriber channels and release any
                // pending NextMsg() calls.
                foreach (Subscription s in subs.Values)
                {
                    s.close();
                }

                subs.Clear();

                // perform appropriate callback is needed for a
                // disconnect;
                if (invokeDelegates && conn.isSetup())
                {
                    scheduleConnEvent(Opts.DisconnectedEventHandler);
                }

                // Go ahead and make sure we have flushed the outbound buffer.
                status = ConnState.CLOSED;
                if (conn.isSetup())
                {
                    if (bw != null)
                    {
                        try
                        {
                            bw.Flush();
                        }
                        catch (Exception) { /* ignore */ }
                    }

                    conn.teardown();
                }

                if (invokeDelegates)
                {
                    scheduleConnEvent(opts.ClosedEventHandler);
                }

                status = closeState;
            }
        }
Exemple #22
0
        // Try to reconnect using the option parameters.
        // This function assumes we are allowed to reconnect.
        //
        // NOTE: locks are manually acquired/released to parallel the NATS
        // go client
        private void doReconnect()
        {
            // We want to make sure we have the other watchers shutdown properly
            // here before we proceed past this point
            waitForExits();

            // FIXME(dlc) - We have an issue here if we have
            // outstanding flush points (pongs) and they were not
            // sent out, but are still in the pipe.

            // Hold manually release where needed below.
            Monitor.Enter(mu);

            // clear any queued pongs, e..g. pending flush calls.
            clearPendingFlushCalls();

            pending = new MemoryStream();
            bw = new BufferedStream(pending);

            // Clear any errors.
            lastEx = null;

            scheduleConnEvent(Opts.DisconnectedEventHandler);

            // TODO:  Look at using a predicate delegate in the server pool to
            // pass a method to, but locking is complex and would need to be
            // reworked.
            Srv cur;
            while ((cur = srvPool.SelectNextServer(Opts.MaxReconnect)) != null)
            {
                url = cur.url;

                lastEx = null;

                // Sleep appropriate amount of time before the
                // connection attempt if connecting to same server
                // we just got disconnected from.
                double elapsedMillis = cur.TimeSinceLastAttempt.TotalMilliseconds;
                double sleepTime = 0;

                if (elapsedMillis < Opts.ReconnectWait)
                {
                    sleepTime = Opts.ReconnectWait - elapsedMillis;
                }

                if (sleepTime <= 0)
                {
                    // Release to allow parallel processes to close,
                    // unsub, etc.  Note:  Use the sleep API - yield is
                    // heavy handed here.
                    sleepTime = 50;
                }

                Monitor.Exit(mu);
                sleep((int)sleepTime);
                Monitor.Enter(mu);

                if (isClosed())
                    break;

                cur.reconnects++;

                try
                {
                    // try to create a new connection
                    createConn(cur);
                }
                catch (Exception)
                {
                    // not yet connected, retry and hold
                    // the lock.
                    lastEx = null;
                    continue;
                }

                // process our connect logic
                try
                {
                    processConnectInit();
                }
                catch (Exception e)
                {
                    lastEx = e;
                    status = ConnState.RECONNECTING;
                    continue;
                }

                try
                {
                    // Send existing subscription state
                    resendSubscriptions();

                    // Now send off and clear pending buffer
                    flushReconnectPendingItems();
                }
                catch (Exception)
                {
                    status = ConnState.RECONNECTING;
                    continue;
                }

                // We are reconnected.
                stats.reconnects++;
                cur.didConnect = true;
                cur.reconnects = 0;
                srvPool.CurrentServer = cur;
                status = ConnState.CONNECTED;

                scheduleConnEvent(Opts.ReconnectedEventHandler);

                // Release lock here, we will return below
                Monitor.Exit(mu);

                // Make sure to flush everything
                // We have a corner case where the server we just
                // connected to has failed as well - let the reader
                // thread detect this and spawn another reconnect 
                // thread to simplify locking.
                try
                {
                    Flush();
                }
                catch (Exception) { }

                return;
            }

            // Call into close.. we have no more servers left..
            if (lastEx == null)
                lastEx = new NATSNoServersException("Unable to reconnect");

            Monitor.Exit(mu);
            Close();
        }
Exemple #23
0
 public OnClosedHandlerArgs(ConnState connState)
 {
     ConnState = connState;
 }
Exemple #24
0
        private static bool OpenConnection(common.wsConnectionInfo wsInfo)
        {
            if (_myClient != null) _myClient.Abort();
            //Basic binding
            _myClient = new ServiceReference1.StockServiceClient("basicEndpoint");
            System.ServiceModel.BasicHttpBinding binding = (_myClient.Endpoint.Binding as System.ServiceModel.BasicHttpBinding);

            //Secure binding
            //_myClient = new ServiceReference1.StockServiceClient("wsEndpoint");
            //System.ServiceModel.WSHttpBinding binding = (_myClient.Endpoint.Binding as System.ServiceModel.WSHttpBinding);

            binding.OpenTimeout = TimeSpan.FromSeconds(wsInfo.timeoutInSecs);
            binding.CloseTimeout = TimeSpan.FromSeconds(wsInfo.timeoutInSecs);
            binding.SendTimeout = TimeSpan.FromSeconds(wsInfo.timeoutInSecs);

            binding.MaxBufferSize = constMaxReceivedMessageSize; //Basic HTTP require MaxBufferSize=MaxReceivedMessageSize
            binding.MaxReceivedMessageSize = constMaxReceivedMessageSize;
            binding.ReaderQuotas.MaxStringContentLength = constMaxStringContentLength;
            binding.ReaderQuotas.MaxBytesPerRead = constMaxBytesPerRead;

            //Proxy  must before setting Endpoint ?
            binding.UseDefaultWebProxy = false;
            if (wsInfo.useProxy)
            {
                if (wsInfo.useDefaultProxy) binding.UseDefaultWebProxy = true;
                else
                {
                    if (wsInfo.proxyAddress.Trim() != "" && wsInfo.proxyPort.Trim() != "")
                    {
                        binding.ProxyAddress = new Uri(wsInfo.proxyAddress.Trim() + ":" + wsInfo.proxyPort.Trim());
                        binding.BypassProxyOnLocal = true;
                        binding.UseDefaultWebProxy = false;
                    }
                }
            }
            //Endpoint settings
            _myClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(wsInfo.URI);
            if (wsInfo.isWindowAuthentication)
            {
                _myClient.ClientCredentials.Windows.ClientCredential.UserName = wsInfo.account;
                _myClient.ClientCredentials.Windows.ClientCredential.Password = wsInfo.password;
            }
            else
            {
                _myClient.ClientCredentials.UserName.UserName = wsInfo.account;
                _myClient.ClientCredentials.UserName.Password = wsInfo.password;
            }

            ServicePointManager.Expect100Continue = false; //loi proxy http://chrishaas.wordpress.com/2009/11/02/fixing-the-remote-server-returned-an-error-417-expectation-failed/
            ServicePointManager.UseNagleAlgorithm = true;
            ServicePointManager.CheckCertificateRevocationList = true;
            ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;

            //For testing
            if (Settings.sysDebugMode)
            {
                _myClient.Endpoint.Address = new System.ServiceModel.EndpointAddress("http://localhost:8731/wsServices/DataLibs");
                _myClient.ClientCredentials.Windows.ClientCredential.UserName = "";
                _myClient.ClientCredentials.Windows.ClientCredential.Password = "";
            }
            //End testing

            _myClient.Open();

            myConnState = ConnState.Connected;
            return true;
        }
Exemple #25
0
        // This will process a disconnect when reconnect is allowed.
        // The lock should not be held on entering this function.
        private void processReconnect()
        {
            lock (mu)
            {
                // If we are already in the proper state, just return.
                if (isReconnecting())
                    return;

                status = ConnState.RECONNECTING;

                if (ptmr != null)
                {
                    ptmr.Stop();
                }

                if (conn.isSetup())
                {
                    conn.teardown();
                }

                new Task(() => { doReconnect(); }).Start();
            }
        }
Exemple #26
0
        // caller must lock.
        private void sendConnect()
        {
            try
            {
                writeString(connectProto());
                bw.Write(pingProtoBytes, 0, pingProtoBytesLen);
                bw.Flush();
            }
            catch (Exception ex)
            {
                if (lastEx == null)
                    throw new NATSException("Error sending connect protocol message", ex);
            }

            string result = null;
            try
            {
                StreamReader sr = new StreamReader(br);
                result = sr.ReadLine();

                // Do not close or dispose the stream reader; 
                // we need the underlying BufferedStream.
            }
            catch (Exception ex)
            {
                throw new NATSConnectionException("Connect read error", ex);
            }

            if (IC.pongProtoNoCRLF.Equals(result))
            {
                status = ConnState.CONNECTED;
                return;
            }
            else
            {
                if (result == null)
                {
                    throw new NATSConnectionException("Connect read protocol error");
                }
                else if (result.StartsWith(IC._ERR_OP_))
                {
                    throw new NATSConnectionException(
                        result.TrimStart(IC._ERR_OP_.ToCharArray()));
                }
                else if (result.StartsWith("tls:"))
                {
                    throw new NATSSecureConnRequiredException(result);
                }
                else
                {
                    throw new NATSException(result);
                }
            }
        }
Exemple #27
0
        // Low level close call that will do correct cleanup and set
        // desired status. Also controls whether user defined callbacks
        // will be triggered. The lock should not be held entering this
        // function. This function will handle the locking manually.
        private void close(ConnState closeState, bool invokeDelegates)
        {
            ConnEventHandler disconnectedEventHandler = null;
            ConnEventHandler closedEventHandler = null;

            lock (mu)
            {
                if (isClosed())
                {
                    status = closeState;
                    return;
                }

                status = ConnState.CLOSED;
            }

            // Kick the routines so they fall out.
            // fch will be closed on finalizer
            kickFlusher();

            // Clear any queued pongs, e.g. pending flush calls.
            clearPendingFlushCalls();

            lock (mu)
            {
                if (ptmr != null)
                    ptmr.Stop();

                // Close sync subscriber channels and release any
                // pending NextMsg() calls.
                foreach (Subscription s in subs.Values)
                {
                    s.closeChannel();
                }

                subs.Clear();

                // perform appropriate callback is needed for a
                // disconnect;
                if (invokeDelegates && conn.isSetup() &&
                    Opts.DisconnectedEventHandler != null)
                {
                    // TODO:  Mirror go, but this can result in a callback
                    // being invoked out of order
                    disconnectedEventHandler = Opts.DisconnectedEventHandler;
                    new Task(() => { disconnectedEventHandler(this, new ConnEventArgs(this)); }).Start();
                }

                // Go ahead and make sure we have flushed the outbound buffer.
                status = ConnState.CLOSED;
                if (conn.isSetup())
                {
                    if (bw != null)
                        bw.Flush();

                    conn.teardown();
                }

                closedEventHandler = opts.ClosedEventHandler;
            }

            if (invokeDelegates && closedEventHandler != null)
            {
                try
                {
                    closedEventHandler(this, new ConnEventArgs(this));
                }
                catch (Exception) { }
            }

            lock (mu)
            {
                status = closeState;
            }
        }
Exemple #28
0
        // This will process a disconnect when reconnect is allowed.
        // The lock should not be held on entering this function.
        private void processReconnect()
        {
            lock (mu)
            {
                // If we are already in the proper state, just return.
                if (isReconnecting())
                    return;

                status = ConnState.RECONNECTING;

                stopPingTimer();

                if (conn.isSetup())
                {
                    conn.teardown();
                }

                Thread t = new Thread(() =>
                {
                    doReconnect();
                });
                t.Name = generateThreadName("Reconnect");
                t.Start();
            }
        }
Exemple #29
0
        // Process a connected connection and initialize properly.
        // Caller must lock.
        private void processConnectInit()
        {
            this.status = ConnState.CONNECTING;

            processExpectedInfo();

            sendConnect();

            new Task(() => { spinUpSocketWatchers(); }).Start();
        }
Exemple #30
0
        // Process a connected connection and initialize properly.
        // Caller must lock.
        private void processConnectInit()
        {
            this.status = ConnState.CONNECTING;

            processExpectedInfo();
            sendConnect();

            // .NET vs go design difference here:
            // Starting the ping timer earlier allows us
            // to assign, and thus, dispose of it if the connection 
            // is disposed before the socket watchers are running.
            // Otherwise, the connection is referenced by an orphaned 
            // ping timer which can create a memory leak.
            startPingTimer();

            new Task(() => { spinUpSocketWatchers(); }).Start();
        }
Exemple #31
0
        private void processDisconnect()
        {
            status = ConnState.DISCONNECTED;
            if (lastEx == null)
                return;

            if (info.SslRequired)
                lastEx = new NATSSecureConnRequiredException();
            else
                lastEx = new NATSConnectionClosedException();
        }
Exemple #32
0
 public void Close()
 {
     _status = ConnState.CLOSED;
     conn.teardown();
 }
Exemple #33
0
        // Try to reconnect using the option parameters.
        // This function assumes we are allowed to reconnect.
        private void doReconnect()
        {
            // We want to make sure we have the other watchers shutdown properly
            // here before we proceed past this point
            waitForExits();



            // FIXME(dlc) - We have an issue here if we have
            // outstanding flush points (pongs) and they were not
            // sent out, but are still in the pipe.

            // Hold the lock manually and release where needed below.
            Monitor.Enter(mu);

            pending = new MemoryStream();
            bw = new BufferedStream(pending);

            // Clear any errors.
            lastEx = null;

            if (Opts.DisconnectedEventHandler != null)
            {
                Monitor.Exit(mu);

                try
                {
                    Opts.DisconnectedEventHandler(this,
                        new ConnEventArgs(this));
                }
                catch (Exception) { }

                Monitor.Enter(mu);
            }

            Srv s;
            while ((s = selectNextServer()) != null)
            {
                if (lastEx != null)
                    break;

                // Sleep appropriate amount of time before the
                // connection attempt if connecting to same server
                // we just got disconnected from.
                double elapsedMillis = s.TimeSinceLastAttempt.TotalMilliseconds;

                if (elapsedMillis < Opts.ReconnectWait)
                {
                    double sleepTime = Opts.ReconnectWait - elapsedMillis;

                    Monitor.Exit(mu);
                    Thread.Sleep((int)sleepTime);
                    Monitor.Enter(mu);
                }
                else
                {
                    // Yield so other things like unsubscribes can
                    // proceed.
                    Monitor.Exit(mu);
                    Thread.Sleep((int)50);
                    Monitor.Enter(mu);
                }

                if (isClosed())
                    break;

                s.reconnects++;

                try
                {
                    // try to create a new connection
                    createConn();
                }
                catch (Exception)
                {
                    // not yet connected, retry and hold
                    // the lock.
                    continue;
                }

                // We are reconnected.
                stats.reconnects++;

                // Clear out server stats for the server we connected to..
                s.didConnect = true;

                // process our connect logic
                try
                {
                    processConnectInit();
                }
                catch (Exception e)
                {
                    lastEx = e;
                    status = ConnState.RECONNECTING;
                    continue;
                }

                s.reconnects = 0;

                // Process CreateConnection logic
                try
                {
                    // Send existing subscription state
                    resendSubscriptions();

                    // Now send off and clear pending buffer
                    flushReconnectPendingItems();

                    // we are connected.
                    status = ConnState.CONNECTED;
                }
                catch (Exception)
                {
                    status = ConnState.RECONNECTING;
                    continue;
                }

                // get the event handler under the lock
                ConnEventHandler reconnectedEh = Opts.ReconnectedEventHandler;

                // Release the lock here, we will return below
                Monitor.Exit(mu);

                // flush everything
                Flush();

                if (reconnectedEh != null)
                {
                    try
                    {
                        reconnectedEh(this, new ConnEventArgs(this));
                    }
                    catch (Exception) { }
                }

                return;

            }

            // we have no more servers left to try.
            if (lastEx == null)
                lastEx = new NATSNoServersException("Unable to reconnect");

            Monitor.Exit(mu);

            Close();
        }
Exemple #34
0
 public void setConnStatus(ConnState newStatus)
 {
     curStatus = newStatus;
 }
Exemple #35
0
        protected virtual void ServicePortConnState(ConnState remoteEndHasBeenClosedState)
        {
            if (BaseState.IsConnected && (dataSP == null || !dataSP.Connected))
            {
                DisposeDataSocket(false);
                SetBaseState(ConnState.ConnectionFailed, "Socket is no longer connected", true);
            }

            if (BaseState.IsConnected && (lastReadResult == ActionResultEnum.ReadRemoteEndHasBeenClosed))
            {
                try
                {
                    if (dataSP != null)
                        DisposeDataSocket();

                    SetBaseState(remoteEndHasBeenClosedState, "Socket remote end has been closed", true);
                }
                catch (System.Exception ex)
                {
                    SetBaseState(ConnState.ConnectionFailed, Fcns.CheckedFormat("Unable to close data socket while handling remote end closed: {0}", ex), true);
                }
            }
        }
Exemple #36
0
 /// <summary>
 /// Реагируем на изменение состояния подключения.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ChangeState(object sender, StateChangeEventArgs e)
 {
     Status = Status ? false : true;
     ConnState?.Invoke(this, new BoolEventArgs(Status));
 }