public void Start() { DontDestroyOnLoad(this); _State = new Disconnected(_Instance); Application.runInBackground = true; Initialize(); }
public void Disconnect() { if (Peer != null) { Peer.Disconnect(); } State = new Disconnected(_instance); }
public void Disconnect() { if(_Peer != null) { _Peer.Disconnect(); _State = new Disconnected(this); } }
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(); }
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); }
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); }
public Task StopHostAsync(bool waitForShutdown, CancellationToken cancellationToken = default(CancellationToken)) { IsHostRunning = false; Disconnected?.Invoke(this, EventArgs.Empty); return(Task.CompletedTask); }
private void OnDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs) { Disconnected?.Invoke(this, eventArgs); }
public MultiplayerSessionManager(IClient client) { Log.Info("Initializing MultiplayerSessionManager..."); Client = client; CurrentState = new Disconnected(); }
protected virtual void OnDisconnected() { DestroyWorkerFacade(); Disconnected?.Invoke(this, EventArgs.Empty); }
/// <summary> /// Triggered when client is disconnected /// </summary> protected virtual void OnDisconnected() { Disconnected?.Invoke(this); }
protected virtual void OnDisconnected(EventArgs e) { Disconnected.SafeInvoke(this, e); }
public void Dispose() { _Connection.Dispose(); Disconnected.Invoke("Being Disposed"); }
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); } }
private void Ws_OnClose(object sender, CloseEventArgs e) { _isDisposed = true; Disconnected?.Invoke(); }
protected virtual void OnDisconnected(Exception e) { Dispose(); Disconnected?.Invoke(this, e); }
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); }
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(); }
private void OnDisconnect() { Disconnected?.Invoke(this, new SocketClientEventArgs()); }
/// <summary> /// Raises the Disconnected event /// </summary> protected virtual void OnDisconnected() { Disconnected?.Invoke(this, EventArgs.Empty); }
internal void CallDisconnected() { Task.Factory.StartNew(() => Disconnected?.Invoke(this, EventArgs.Empty)); }
private void DisconnectAndDispose() { Disconnected?.Invoke(this, null); Dispose(); }
/// <summary> /// To call the event <see cref="Disconnected"/>. /// </summary> private void RaiseDisconnected() { ConnectionState = ConnectionStates.Disconnected; Disconnected?.Invoke(); }
private void onDisconnect(object sender, ConnEventArgs args) { Log.Info("Lost connection to NATS."); Disconnected?.Invoke(this, EmptyServeEventArgs); }
protected void OnDisconnected(INetworkLayerInterface sender, ConnectionEventArgs connectionEventArgs) { Disconnected?.Invoke(sender, connectionEventArgs); }
/// <summary> /// Raises client disconnected event /// </summary> protected virtual void ClientDisconnected(SocketBase client) { Disconnected?.Invoke((TClient)client); }
protected void _invokeDisconnected(DisconnectArgs e) { Disconnected.Invoke(this, e); }
public void Disconnect(DisconnectReason reason, string details) { Disconnected?.Invoke(this, EventArgs.Empty); }
protected void OnDisconnected(NamedPipeConnection <Message, Message> connection) { Disconnected?.Invoke(connection); }
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}"); } }
/// <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(); } }
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(); } }
protected virtual void OnDisconnected() { Disconnected?.Invoke(this, new EventArgs()); }
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; } }
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}"); } }
///<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); }
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; } }
private void OnDisconnected() { Disconnected?.Invoke(this); }
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; }
public virtual void OnServiceDisconnected(ComponentName name) { IsConnected = false; Disconnected?.Invoke(name); }