コード例 #1
0
ファイル: PhotonEngine.cs プロジェクト: AroraAnkush/Main
 public void Start()
 {
     DontDestroyOnLoad(this);
     _State = new Disconnected(_Instance);
     Application.runInBackground = true;
     Initialize();
 }
コード例 #2
0
 public void Disconnect()
 {
     if (Peer != null)
     {
         Peer.Disconnect();
     }
     State = new Disconnected(_instance);
 }
コード例 #3
0
ファイル: PhotonEngine.cs プロジェクト: AroraAnkush/Main
 public void Disconnect()
 {
     if(_Peer != null)
     {
         _Peer.Disconnect();
         _State = new Disconnected(this);
     }
 }
コード例 #4
0
		public void Connect_Results_In_An_Invalid_Operation_Exception()
		{
			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _connectionManager = Substitute.For<IConnectionManager>();
			var _context = Substitute.For<IBusContext>();

			var _SUT = new Disconnected(
				_busConfirguration,
				_connectionManager,
				_context);

			_SUT.Connect();
		}
コード例 #5
0
		public void Publish_Where_No_Publication_Configurations_Which_Results_In_A_NoConfigurationFound_Result()
		{
			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _connectionManager = Substitute.For<IConnectionManager>();
			var _context = Substitute.For<IBusContext>();

			var _SUT = new Disconnected(
				_busConfirguration,
				_connectionManager,
				_context);

			var _theEvent = new MyEvent(Guid.NewGuid(), null, "Some detail", 1);
			var _publicationResult = _SUT.PublishAsync(_theEvent);
			_publicationResult.Wait();

			Assert.AreEqual(PMCG.Messaging.PublicationResultStatus.NoConfigurationFound, _publicationResult.Result.Status);
		}
コード例 #6
0
		public void Ctor_Success()
		{
			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			_busConfigurationBuilder
				.RegisterPublication<MyEvent>(
					TestingConfiguration.ExchangeName,
					typeof(MyEvent).Name);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _connectionManager = Substitute.For<IConnectionManager>();
			var _context = Substitute.For<IBusContext>();

			var _SUT = new Disconnected(
				_busConfirguration,
				_connectionManager,
				_context);

			Assert.IsNotNull(_SUT);
		}
コード例 #7
0
ファイル: RSessionMock.cs プロジェクト: jingmouren/RTVS
 public Task StopHostAsync(bool waitForShutdown, CancellationToken cancellationToken = default(CancellationToken))
 {
     IsHostRunning = false;
     Disconnected?.Invoke(this, EventArgs.Empty);
     return(Task.CompletedTask);
 }
コード例 #8
0
ファイル: ManagedMqttClient.cs プロジェクト: ze-vs/MQTTnet
 private void OnDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs)
 {
     Disconnected?.Invoke(this, eventArgs);
 }
コード例 #9
0
 public MultiplayerSessionManager(IClient client)
 {
     Log.Info("Initializing MultiplayerSessionManager...");
     Client       = client;
     CurrentState = new Disconnected();
 }
コード例 #10
0
 protected virtual void OnDisconnected()
 {
     DestroyWorkerFacade();
     Disconnected?.Invoke(this, EventArgs.Empty);
 }
コード例 #11
0
ファイル: SocketBase.cs プロジェクト: ciker/twino
 /// <summary>
 /// Triggered when client is disconnected
 /// </summary>
 protected virtual void OnDisconnected()
 {
     Disconnected?.Invoke(this);
 }
コード例 #12
0
ファイル: Connection.cs プロジェクト: Xellzul/Firebridge
 protected virtual void OnDisconnected(EventArgs e)
 {
     Disconnected.SafeInvoke(this, e);
 }
コード例 #13
0
 public void Dispose()
 {
     _Connection.Dispose();
     Disconnected.Invoke("Being Disposed");
 }
コード例 #14
0
ファイル: SerialMonitor.cs プロジェクト: retrospy/RetroSpy
        private void Tick(object sender, EventArgs e)
        {
            if (_datPort == null || !_datPort.IsOpen || PacketReceived == null)
            {
                return;
            }

            // Try to read some data from the COM port and append it to our localBuffer.
            // If there's an IOException then the device has been disconnected.
            try
            {
                int readCount = _datPort.BytesToRead;
                if (readCount < 1)
                {
                    return;
                }

                byte[] readBuffer = new byte[readCount];
                _ = _datPort.Read(readBuffer, 0, readCount);
                //_datPort.DiscardInBuffer();
                _localBuffer.AddRange(readBuffer);
            }
            catch (IOException)
            {
                Stop();
                Disconnected?.Invoke(this, EventArgs.Empty);
                return;
            }

            // Try and find 2 splitting characters in our buffer.
            int lastSplitIndex = _localBuffer.LastIndexOf(0x0A);

            if (lastSplitIndex <= 1)
            {
                return;
            }

            int sndLastSplitIndex = _localBuffer.LastIndexOf(0x0A, lastSplitIndex - 1);

            if (lastSplitIndex == -1)
            {
                return;
            }

            // Grab the latest packet out of the buffer and fire it off to the receive event listeners.
            int packetStart = sndLastSplitIndex + 1;
            int packetSize  = lastSplitIndex - packetStart;

            if (_printerMode)
            {
                byte[] array       = _localBuffer.ToArray();
                string lastCommand = Encoding.UTF8.GetString(array, 0, lastSplitIndex);

                if (lastCommand.Contains("# Finished Pretending To Print for fun!") || lastCommand.Contains("// Timed Out (Memory Waterline: 4B out of 400B)"))
                {
                    PacketReceived(this, new PacketDataEventArgs(_localBuffer.GetRange(0, lastSplitIndex).ToArray()));

                    // Clear our buffer up until the last split character.
                    _localBuffer.RemoveRange(0, lastSplitIndex);
                }
            }
            else
            {
                PacketReceived(this, new PacketDataEventArgs(_localBuffer.GetRange(packetStart, packetSize).ToArray()));

                // Clear our buffer up until the last split character.
                _localBuffer.RemoveRange(0, lastSplitIndex);
            }
        }
コード例 #15
0
ファイル: LivecoinClient.cs プロジェクト: w1r2p1/OsEngineMono
        private void Ws_OnClose(object sender, CloseEventArgs e)
        {
            _isDisposed = true;

            Disconnected?.Invoke();
        }
コード例 #16
0
ファイル: Device.cs プロジェクト: nuhure/ScriptPlayer
 protected virtual void OnDisconnected(Exception e)
 {
     Dispose();
     Disconnected?.Invoke(this, e);
 }
コード例 #17
0
		public void State_Changed_Where_Connection_Is_Established_Results_In_Transition_To_Connected_State()
		{
			var _connectionEstablishedWaitHandle = new AutoResetEvent(false);
			var _transitionBeingAttemptedWaitHandle = new AutoResetEvent(false);

			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _connectionManager = Substitute.For<IConnectionManager>();
			var _context = Substitute.For<IBusContext>();

			_connectionManager.IsOpen.Returns(true);
			_connectionManager
				.When(connectionManager => connectionManager.Open())
				.Do(callInfo => { _connectionEstablishedWaitHandle.WaitOne(); });

			var _SUT = new Disconnected(
				_busConfirguration,
				_connectionManager,
				_context);

			_context.State.Returns(callInfo => _SUT);
			State _capturedState = null;
			_context.When(context => context.State = Arg.Any<State>()).Do(callInfo =>
				{
					_capturedState = callInfo[0] as State;
					_transitionBeingAttemptedWaitHandle.Set();
				});
			_connectionEstablishedWaitHandle.Set();				// Allow ConnectionManagers Open method to complete
			_transitionBeingAttemptedWaitHandle.WaitOne();		// Wait on state transition completion

			Assert.IsInstanceOf<Connected>(_capturedState);
		}
コード例 #18
0
		public void Close_Results_In_Transition_To_Closed_State()
		{
			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _connectionManager = Substitute.For<IConnectionManager>();
			var _context = Substitute.For<IBusContext>();

			var _SUT = new Disconnected(
				_busConfirguration,
				_connectionManager,
				_context);

			_context.State.Returns(callInfo => _SUT);
			State _capturedState = null;
			_context.When(context => context.State = Arg.Any<State>()).Do(callInfo => _capturedState = callInfo[0] as State);
			_SUT.Close();

			Assert.IsInstanceOf<Closed>(_capturedState);
			_connectionManager.Received().Close();
		}
コード例 #19
0
 private void OnDisconnect()
 {
     Disconnected?.Invoke(this, new SocketClientEventArgs());
 }
コード例 #20
0
 /// <summary>
 /// Raises the Disconnected event
 /// </summary>
 protected virtual void OnDisconnected()
 {
     Disconnected?.Invoke(this, EventArgs.Empty);
 }
コード例 #21
0
ファイル: TcpClient.cs プロジェクト: gkurbesov/C4C.Socket
 internal void CallDisconnected()
 {
     Task.Factory.StartNew(() => Disconnected?.Invoke(this, EventArgs.Empty));
 }
コード例 #22
0
 private void DisconnectAndDispose()
 {
     Disconnected?.Invoke(this, null);
     Dispose();
 }
コード例 #23
0
 /// <summary>
 /// To call the event <see cref="Disconnected"/>.
 /// </summary>
 private void RaiseDisconnected()
 {
     ConnectionState = ConnectionStates.Disconnected;
     Disconnected?.Invoke();
 }
コード例 #24
0
 private void onDisconnect(object sender, ConnEventArgs args)
 {
     Log.Info("Lost connection to NATS.");
     Disconnected?.Invoke(this, EmptyServeEventArgs);
 }
コード例 #25
0
 protected void OnDisconnected(INetworkLayerInterface sender, ConnectionEventArgs connectionEventArgs)
 {
     Disconnected?.Invoke(sender, connectionEventArgs);
 }
コード例 #26
0
ファイル: ConnectorBase.cs プロジェクト: Akrotiri/twino
 /// <summary>
 /// Raises client disconnected event
 /// </summary>
 protected virtual void ClientDisconnected(SocketBase client)
 {
     Disconnected?.Invoke((TClient)client);
 }
コード例 #27
0
 protected void _invokeDisconnected(DisconnectArgs e)
 {
     Disconnected.Invoke(this, e);
 }
コード例 #28
0
 public void Disconnect(DisconnectReason reason, string details)
 {
     Disconnected?.Invoke(this, EventArgs.Empty);
 }
コード例 #29
0
 protected void OnDisconnected(NamedPipeConnection <Message, Message> connection)
 {
     Disconnected?.Invoke(connection);
 }
コード例 #30
0
        public void AcceptCallback(IAsyncResult _asyncResult)
        {
            //Get the socket that handles the client request.
            var _listenerSocket = (Socket)_asyncResult.AsyncState;

            if (_listenerSocket == null)
            {
                return;
            }

            //Get clientSocket
            try
            {
                decoderSocket = _listenerSocket.EndAccept(_asyncResult);

                //Shutdown listener only one client allowed
                listenerSocket.Close();
                listenerSocket = null;
            }
            catch (Exception ex)
            {
                Logger.WriteDebug($"{decoderName}: {ex} -> {ex.Message}");
            }

            //Check Connection
            if (decoderSocket == null || !decoderSocket.Connected)
            {
                Logger.WriteDebug($"{decoderName}: Disconnected");
                decoderStatus = ConnectionStatus.ClientDisconnected;

                //Raise event
                Disconnected.RaiseEvent(this, null);
                //Try to reconnect again;
                Restart();

                return;
            }


            //Start to receive
            try
            {
                Logger.WriteDebug($"{decoderName}: Connection from {decoderSocket.RemoteEndPoint}");
                decoderStatus = ConnectionStatus.ClientConnected;

                restartAttempts = 0;
                pingAttempts    = 0;

                //Send LoginString
                Send(loginString);

                // Begin receiving the data from the remote device.
                var _state = new StateObject();
                decoderSocket.BeginReceive(_state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, _state);

                //Raise event
                Connected.RaiseEvent(this, null);
            }
            catch (Exception ex)
            {
                Logger.WriteDebug($"{decoderName}: {ex} -> {ex.Message}");
            }
        }
コード例 #31
0
        /// <summary>
        /// The ClientBase startup method.
        /// </summary>
        /// <returns></returns>
        public async Task <ClientBase> StartAsync()
        {
            if (string.IsNullOrEmpty(ServerIP) || ServerPort <= 0)
            {
                Logger.Error("Cannot start as either server ip or port is invalid.");
                return(this);
            }

            if (IsConnected)
            {
                Logger.Error("Client is already connected with the server.");
                return(this);
            }

            int connTries = 0;

            try {
                await ClientSemaphore.WaitAsync().ConfigureAwait(false);

                while (connTries < MAX_CONNECTION_RETRY_COUNT)
                {
                    if (!Helpers.IsServerOnline(ServerIP))
                    {
                        Logger.Error($"Server is offline. RETRY_COUNT -> {connTries}");
                        connTries++;
                        continue;
                    }

                    try {
                        Connector = new TcpClient(ServerIP, ServerPort);
                    }
                    catch (SocketException) {
                        connTries++;
                        continue;
                    }
                    catch (Exception e) {
                        Logger.Exception(e);
                        break;
                    }

                    if (IsConnected)
                    {
                        break;
                    }

                    connTries++;
                }

                if (connTries >= MAX_CONNECTION_RETRY_COUNT && !IsConnected)
                {
                    Logger.Error($"Could not connect with server even after {connTries} retry count.");
                    return(this);
                }

                if (!IsConnected)
                {
                    Logger.Error($"Could not connect with server. Server might be offline or unreachable!");
                    return(this);
                }

                Logger.Info("Connected to server.");
                Connected?.Invoke(this, new OnConnectedEventArgs(DateTime.Now, ServerIP, ServerPort));

                Helpers.InBackgroundThread(async() => {
                    await ClientReceivingSemaphore.WaitAsync().ConfigureAwait(false);

                    while (IsConnected)
                    {
                        try {
                            NetworkStream?stream = Connector?.GetStream();

                            if (stream == null)
                            {
                                continue;
                            }

                            IsReceiving = true;

                            if (!stream.DataAvailable)
                            {
                                await Task.Delay(1).ConfigureAwait(false);
                                continue;
                            }

                            byte[] readBuffer = new byte[8000];
                            int dataCount     = stream.Read(readBuffer, 0, readBuffer.Length);

                            if (dataCount <= 0 || readBuffer.Length <= 0)
                            {
                                await Task.Delay(1).ConfigureAwait(false);
                                continue;
                            }

                            string received = Encoding.ASCII.GetString(readBuffer);

                            if (string.IsNullOrEmpty(received))
                            {
                                await Task.Delay(1).ConfigureAwait(false);
                                continue;
                            }

                            BaseResponse receivedObj = JsonConvert.DeserializeObject <BaseResponse>(received);

                            if (PreviousResponse != null && PreviousResponse.Equals(receivedObj))
                            {
                                await Task.Delay(1).ConfigureAwait(false);
                                continue;
                            }

                            ResponseReceived?.Invoke(this, new OnResponseReceivedEventArgs(DateTime.Now, receivedObj, received));
                            PreviousResponse = receivedObj;
                        }
                        catch (SocketException s) {
                            Logger.Trace($"SOCKET EXCEPTION -> {s.SocketErrorCode.ToString()}");
                            break;
                        }
                        catch (Exception e) {
                            Logger.Error($"EXCEPTION -> {e.Message}");
                            continue;
                        }
                    }

                    ClientReceivingSemaphore.Release();
                    Logger.Info("Disconnected from server.");
                    IsReceiving = false;
                    Disconnected?.Invoke(this, new OnDisconnectedEventArgs(DateTime.Now, false, ServerIP, ServerPort, true));
                }, "Client Receiving Thread", true);

                return(this);
            }
            finally {
                ClientSemaphore.Release();
            }
        }
コード例 #32
0
        public void ReceiveCallback(IAsyncResult _asyncResult)
        {
            // Retrieve the state object and the handler socket from the asynchronous state object.
            var _state = (StateObject)_asyncResult.AsyncState;

            if (_state == null || decoderSocket == null)
            {
                return;
            }

            var _socketError = new SocketError();
            var _bytesRead   = 0;

            try
            {
                // Read data from the remote device.
                _bytesRead = decoderSocket.EndReceive(_asyncResult, out _socketError);

                //EndRecieve returns x bytes -> connection ok
                if (_bytesRead > 0)
                {
                    //Store the data received so far
                    _state.Data += Encoding.ASCII.GetString(_state.Buffer, 0, _bytesRead);

                    //Split each frame
                    var _dataArray = _state.Data.Split(new[]
                    {
                        decoderEtxString
                    }, StringSplitOptions.RemoveEmptyEntries);
                    if (_dataArray != null && _dataArray.Count() > 0)
                    {
                        //Loop through all frames
                        foreach (var _data in _dataArray)
                        {
                            Logger.WriteDebug($"{decoderName}: Message -> {_data}");

                            //Remove frame + etx from buffer
                            _state.Data = _state.Data.Replace(_data + decoderEtxString, "");
                            //Raise event
                            MessageReceived.RaiseEvent(this, new MessageEventArgs(_data));
                        }
                    }

                    if (decoderSocket != null && decoderSocket.Connected)
                    {
                        //Start receive again
                        decoderSocket.BeginReceive(_state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback,
                                                   _state);
                    }
                }
                //EndRecieve returns 0 bytes -> connection have been closed by the remote endpoint.
                else if (_bytesRead == 0 && decoderStatus == ConnectionStatus.ClientConnected)
                {
                    Logger.WriteDebug($"{decoderName}: Connection closed from client");

                    //Raise event
                    Disconnected.RaiseEvent(this, null);
                    //Try to reconnect again;
                    Restart();
                }
                else if (_socketError != SocketError.Success)
                {
                    Logger.WriteDebug($"{decoderName}: SocketError -> {_socketError}");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteDebug($"{decoderName}: Error on receive -> {ex.Message}");
                //Raise event
                Disconnected.RaiseEvent(this, null);
                //Try to reconnect again;
                Restart();
            }
        }
コード例 #33
0
 protected virtual void OnDisconnected()
 {
     Disconnected?.Invoke(this, new EventArgs());
 }
コード例 #34
0
 public void OnStatusChanged(StatusCode statusCode)
 {
     print(statusCode.ToString());
     switch (statusCode)
     {
         case StatusCode.Connect:
             Peer.EstablishEncryption();
             break;
         case StatusCode.Disconnect:
         case StatusCode.DisconnectByServer:
         case StatusCode.DisconnectByServerLogic:
         case StatusCode.DisconnectByServerUserLimit:
         case StatusCode.ExceptionOnConnect:
         case StatusCode.TimeoutDisconnect:
             Controller.OnDisconnect("" + statusCode);
             State = new Disconnected(_instance);
             break;
         case StatusCode.EncryptionEstablished:
             State = new Connected(_instance);
             break;
         default:
             Controller.OnUnexpectedStatusCode(statusCode);
             State = new Disconnected(_instance);
             break;
     }
 }
コード例 #35
0
        public void Start()
        {
            try
            {
                if (Regex.IsMatch(decoderServer,
                                  @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")
                    )
                {
                    // the string is an IP
                    decoderIpAddress = IPAddress.Parse(decoderServer);
                }
                else if (Regex.IsMatch(decoderServer,
                                       @"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"))
                {
                    // the string is a host
                    var _ipHostInfo = Dns.GetHostEntry(decoderServer);
                    decoderIpAddress = _ipHostInfo.AddressList[0];
                }
                else
                {
                    Logger.WriteDebug($"{decoderName}: Wrong setting -> decoderServer");
                    Disconnected.RaiseEvent(this, null);
                    return;
                }

                if (decoderPort <= 0 || decoderPort >= 65535)
                {
                    Logger.WriteDebug($"{decoderName}: Wrong setting -> decoderPort");
                    Disconnected.RaiseEvent(this, null);
                    return;
                }

                if (string.IsNullOrEmpty(decoderEtxString))
                {
                    Logger.WriteDebug($"{decoderName}: Wrong setting -> decoderEtxString");
                    Disconnected.RaiseEvent(this, null);
                    return;
                }

                //Timer for auto reconnect
                restartAttempts = 0;
                restartTimer    = new Timer
                {
                    Interval  = 1000, //will be increased in handler
                    AutoReset = false
                };
                restartTimer.Elapsed += reconnectTimer_Elapsed;
                restartTimer.Stop();

                //Timeout for receive
                sendTimeout = new Timer
                {
                    Interval  = TIMEOUT_INTERVAL,
                    AutoReset = false
                };
                sendTimeout.Elapsed += sendTimeout_Elapsed;
                sendTimeout.Stop();

                //Connect to TCP/IP-Server
                StartListening();
            }
            catch (Exception ex)
            {
                Logger.WriteDebug($"{decoderName}: {ex} -> {ex.Message}");
            }
        }
コード例 #36
0
 ///<summary>Signals that the Subscription we use for receiving
 ///our RPC replies was disconnected while we were
 ///waiting.</summary>
 ///<remarks>
 /// Fires the Disconnected event.
 ///</remarks>
 public virtual void OnDisconnected()
 {
     Disconnected?.Invoke(this, null);
 }
コード例 #37
0
ファイル: PhotonEngine.cs プロジェクト: AroraAnkush/Main
    public void OnStatusChanged(StatusCode statusCode)
    {
        switch(statusCode)
        {
            case StatusCode.Connect:
                _Peer.EstablishEncryption();
                break;
            case StatusCode.Disconnect:
                
            case StatusCode.DisconnectByServer:
               
            case StatusCode.DisconnectByServerLogic:
                
            case StatusCode.DisconnectByServerUserLimit:
                
            case StatusCode.ExceptionOnConnect:
                
            case StatusCode.TimeoutDisconnect:

                Controller.OnDisconnected("" + statusCode);
                _State = new Disconnected(this);
                break;

            case StatusCode.EncryptionEstablished:
                _State = new Connected(this);
                break;
            default:
                Controller.OnUnexpectedStatusCode(statusCode);
                _State = new Disconnected(this);
                break;
        }
    }
コード例 #38
0
 private void OnDisconnected()
 {
     Disconnected?.Invoke(this);
 }
コード例 #39
0
        private async Task Reconnect()
        {
            if (cts.Token.IsCancellationRequested)
            {
                return;
            }
            if (isReconnecting)
            {
                return;
            }
            isReconnecting = true;
            tcpClient?.Dispose();
            tcpClient = null;

            if (reconnectFailed)
            {
                throw new InvalidOperationException("Reconnect failed");
            }
            if (wasConnected)
            {
                logger?.LogDebug("ModbusClient.Reconnect fire disconnected event.");
                Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
            }

            var timeout    = 2;
            var maxTimeout = 20;
            var startTime  = DateTime.UtcNow;

            while (!cts.Token.IsCancellationRequested)
            {
                try
                {
                    tcpClient = new TcpClient(AddressFamily.InterNetworkV6);
                    tcpClient.Client.DualMode = true;
                    var connectTask = tcpClient.ConnectAsync(Host, Port);
                    if (await Task.WhenAny(connectTask, Task.Delay(TimeSpan.FromSeconds(timeout), cts.Token)) == connectTask)
                    {
                        logger?.LogInformation("ModbusClient.Reconnect connected.");
                        tcpClient.SendTimeout    = SendTimeout;
                        tcpClient.ReceiveTimeout = ReceiveTimeout;
                    }
                    else if (cts.Token.IsCancellationRequested)
                    {
                        logger?.LogWarning("ModbusClient.Reconnect was cancelled.");
                        return;
                    }
                    else
                    {
                        logger?.LogWarning($"ModbusClient.Reconnect failed to connect within {timeout} seconds.");
                        timeout += 2;
                        if (timeout > maxTimeout)
                        {
                            timeout = maxTimeout;
                        }
                        throw new SocketException((int)SocketError.TimedOut);
                    }
                }
                catch (SocketException) when(ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow <= startTime + ReconnectTimeSpan)
                {
                    await Task.Delay(1000, cts.Token);

                    continue;
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "ModbusClient.Reconnect failed.");
                    reconnectFailed = true;
                    if (isDisposed)
                    {
                        return;
                    }
                    if (wasConnected)
                    {
                        throw new IOException("Server connection lost, reconnect failed", ex);
                    }
                    else
                    {
                        throw new IOException("Could not connect to the server", ex);
                    }
                }

                wasConnected = true;
                logger?.LogDebug("ModbusClient.Reconnect fire connected event.");
                Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
                break;
            }

            isReconnecting = false;
        }
コード例 #40
0
 public virtual void OnServiceDisconnected(ComponentName name)
 {
     IsConnected = false;
     Disconnected?.Invoke(name);
 }