private void OnSelectedConnectionChanged(Connection previous) { if (Connection == null) { return; } if (Connection == _selectConnectionItem) { return; } if (Connection == _addNewConnectionItem) { Task.Delay(100) .ContinueWith(task => { _connection = previous; NotifyOfPropertyChange(() => Connection); }) .ContinueWith(task => { ShowConnectionDialog(); }); } else { // Save selected connection to file to enable auto-connect var viewModel = new ConnectionViewModel(Runtime, ConnectionType); viewModel.SaveConnectionFile(Connection); // Invoke delegate that will handle the connection change OnConnectionChanged?.Invoke(Connection); } }
private void ReconnectLoop() { var count = _maxRetries; while (!_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource.Token.WaitHandle.WaitOne(_reconnectInterval); try { lock (_gate) { OnConnectionChanged?.Invoke(this, new ConnectionChangedEventArgs(ConnectionState.Connecting)); _client = _clientFactory(); AttachEvents(_client); _isFaulted = false; OnConnectionChanged?.Invoke(this, new ConnectionChangedEventArgs(ConnectionState.Connected)); } return; } catch (OperationCanceledException) { break; } catch (Exception error) { OnConnectionChanged?.Invoke(this, new ConnectionChangedEventArgs(ConnectionState.Faulted, error)); if (--count < 0) { break; } } } }
/// <summary> /// Close the communication /// </summary> public void Close() { _isOpen = false; _client?.Close(); _listener?.Stop(); OnConnectionChanged?.Invoke(false); }
private void ConnectionChanged(object sender, ConnectionChangedEventArgs args) { OnConnectionChanged?.Invoke(this, args); if (args.State == ConnectionState.Faulted) { Reconnect(); } }
private void Connect(string targetHost) { if (openConnection.IsNull()) { openConnection = new Connection(targetHost, sendFromIndividualThread); openConnection.ConnectionOpened += ConnectionOpened; openConnection.ConnectionClosed += ConnectionClosed; openConnection.MessageReceived += MessageReceived; OnConnectionChanged.SafeInvoke(openConnection); } openConnection.Connect(); }
public unsafe void Update() { if (!IsConnected) { if (_connected) { OnConnectionChanged?.Invoke(this, _connected = false); } return; } var btn = GlfwProvider.GLFW.Value.GetJoystickButtons(Index, out var btnCount); var axes = GlfwProvider.GLFW.Value.GetJoystickAxes(Index, out var axisCount); var hats = GlfwProvider.GLFW.Value.GetJoystickHats(Index, out var hatCount); EnsureButtonSize(btnCount); EnsureAxesSize(axisCount); EnsureHatSize(hatCount); for (var i = 0; i < btnCount; i++) { _buttons[i] = new Button(ButtonName.Unknown, i, btn[i] == (int)InputAction.Press); } for (var i = 0; i < axisCount; i++) { _axes[i] = new Axis(i, axes[i]); } for (var i = 0; i < hatCount; i++) { _hats[i] = new Hat ( i, hats[i] switch { JoystickHats.Centered => Position2D.Centered, JoystickHats.Up => Position2D.Up, JoystickHats.Right => Position2D.Right, JoystickHats.Down => Position2D.Down, JoystickHats.Left => Position2D.Left, JoystickHats.RightUp => Position2D.UpRight, JoystickHats.RightDown => Position2D.DownRight, JoystickHats.LeftUp => Position2D.UpLeft, JoystickHats.LeftDown => Position2D.UpRight, _ => Position2D.Centered }
public RemoteUnityAgentHost() { var container = new GameObject("RemoteUnityHostAgent"); var host = container.AddComponent <TachyonUnityHost>(); host.OnClientConnected += (c) => { OnConnectionChanged?.Invoke(true); _connected = true; }; host.OnClientDisconnected += (c) => { OnConnectionChanged?.Invoke(false); _connected = false; }; _nativeAgent = new NativeUnityDriverAgent(); _scheneObject = container; _host = host; }
/// <summary> /// connect to server /// </summary> /// <param name="url">server url address</param> /// <param name="isWebsocket"></param> public override void Connect(string url) { #if (!NETSTANDARD2_0 && !NET45) if (ProtocolType != ClientProtocolType.HttpDuplex) { throw new NotSupportedException(); } #endif if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { throw new Exception("url is not valid"); } else if (uri.Port <= 0) { throw new Exception("port is not valid"); } if (uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("ws", StringComparison.OrdinalIgnoreCase)) { ProtocolType = ClientProtocolType.WebSocket; } ServerUrl = url; string hostName = uri.Host; base.Connect(hostName, uri.Port); #if (NET40 || NET35) SendFirstLineData(); #else SendFirstLineData().GetAwaiter().GetResult(); #endif GetClientIdIfNeed(); IsConnected = true; RunPriorities(); StartToReadingClientData(); if (IsAutoReconnecting) { OnConnectionChanged?.Invoke(ConnectionStatus.Reconnected); } else { OnConnectionChanged?.Invoke(ConnectionStatus.Connected); } }
void AcceptClients() { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = $"TCP RPC Acceptor Thread {Thread.CurrentThread.ManagedThreadId}"; } while (true) { var client = _listener.AcceptTcpClient(); var pump = new FramePump(client.GetStream()); var outboundEndpoint = new OutboundTcpEndpoint(this, pump); var inboundEndpoint = _rpcEngine.AddEndpoint(outboundEndpoint); pump.FrameReceived += inboundEndpoint.Forward; var connection = new Connection(this, client, pump, outboundEndpoint, inboundEndpoint); lock (_reentrancyBlocker) { ++ConnectionCount; _connections.Add(connection); OnConnectionChanged?.Invoke(this, new ConnectionEventArgs(connection)); connection.Start(); } connection.PumpRunner.Start(); } } catch (SocketException) { // Listener was stopped. Maybe a little bit rude, but this is // our way of shutting down the acceptor thread. } catch (System.Exception exception) { // Any other exception might be due to some other problem. Logger.LogError(exception.Message); } }
static void OpenFixConn() { try { string fixClientConf = Environment.CurrentDirectory + @"\" + SystemConfigurations.GetAppSetting("FixClientConfPath"); SessionSettings settings = new SessionSettings(fixClientConf); OnConnectionChanged d = new OnConnectionChanged(FixConnChanged); _app = new ClientApp(d); //_app.OnStatusChanged+= FileStoreFactory storeFactory = new FileStoreFactory(settings); FileLogFactory logFactory = new FileLogFactory(settings); MessageFactory messageFactory = new DefaultMessageFactory(); _initiator = new SocketInitiator(_app, storeFactory, settings, logFactory, messageFactory); _initiator.start(); } catch (Exception ex) { Console.WriteLine(ex); } }
void AcceptClients(TcpListener listener) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = $"TCP RPC Acceptor Thread {Thread.CurrentThread.ManagedThreadId}"; } while (true) { var client = listener.AcceptTcpClient(); var connection = new Connection(this, client); lock (_reentrancyBlocker) { ++ConnectionCount; _connections.Add(connection); OnConnectionChanged?.Invoke(this, new ConnectionEventArgs(connection)); connection.Start(); } } } catch (SocketException) { // Listener was stopped. Maybe a little bit rude, but this is // our way of shutting down the acceptor thread. } catch (ThreadInterruptedException) { Logger.LogError($"{Thread.CurrentThread.Name} interrupted at {Environment.StackTrace}"); } catch (System.Exception exception) { // Any other exception might be due to some other problem. Logger.LogError(exception.Message); } }
private void OnSelectedConnectionChanged(Connection previous) { if (Connection == _selectConnectionItem) { return; } // If previous connection was disposed if (previous == null) { return; } if (Connection == _addNewConnectionItem) { _connection = previous; NotifyOfPropertyChange(() => Connection); ShowConnectionDialog(); return; } // Invoke delegate that will handle the connection change OnConnectionChanged?.Invoke(Connection); }
public ClientApp(OnConnectionChanged del) { _delConChanged = del; }
/// <summary> /// 1. release all resources /// 2. connect and login /// 3. subscribe saved channel /// 4. subscribe pending channel /// </summary> /// <returns></returns> /// private async void CloseCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { lock (this) { if (_isTimerBusy) { return; } _isTimerBusy = !_isTimerBusy; } try { if (_ws != null && _ws.State != this.State) { this.State = _ws.State; OnConnectionChanged?.Invoke(this, State); } if (this.IsStartRequested && _ws.State != WebSocketState.Open) //reconnect { await this.CloseSocket(); Console.WriteLine($"socket state = {_ws.State} trying to reconnect ..."); //cancel the receive thread loop if (_cts.Token.CanBeCanceled) { _cts.Cancel(); _cts = new CancellationTokenSource(); } _ws.Abort(); _ws.Dispose(); _ws = null; _ws = new ClientWebSocket(); await _ws.ConnectAsync(new Uri(_url), _cts.Token); this.receive(); //start a new thread to receive data Thread.Sleep(10000); Console.WriteLine($"socket state = {_ws.State}"); } else if (this.IsStartRequested && _ws.State == WebSocketState.Open) //send pending channel { var tnow = DateTime.UtcNow.GetUnixTimeFromUTC(); if (tnow - _lastReceiveTime > _receiveOvertimeSeconds) { _lastReceiveTime = tnow; OnReceiveOverTime?.Invoke(this, (int)(tnow - _lastReceiveTime)); } if (_pendingChannels.Count > 0) { string channel; while (_pendingChannels.TryDequeue(out channel)) { await this.SendAsync(channel); } } } else if (!this.IsStartRequested && _ws.State == WebSocketState.Open) //stop { await _ws.CloseOutputAsync(WebSocketCloseStatus.Empty, null, _cts.Token); _cts.Cancel(); } } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("reconnecting after 10 seconds..."); Thread.Sleep(10000); } finally { _isTimerBusy = !_isTimerBusy; } }
public void Update() { if (!GlfwProvider.GLFW.Value.GetGamepadState(Index, out var state)) { // Detect when this gamepad disconnects if (_connected) { OnConnectionChanged?.Invoke(this, false); _connected = false; } return; } // Detect when this gamepad connects if (!_connected) { OnConnectionChanged?.Invoke(this, true); _connected = true; } // Buttons for (var i = 0; i < GamepadButtonCount; i++) { if ((_buttons[i].Pressed ? 1 : 0) != state.Buttons[i]) { (_buttons[i].Pressed ? ButtonUp : ButtonDown)?.Invoke (this, _buttons[i] = new Button((ButtonName)i, i, state.Buttons[i] == 1)); } _buttons[i] = new Button((ButtonName)i, i, state.Buttons[i] == 1); } // Left Thumbstick var thumbstick0 = new Thumbstick(0, Deadzone.Apply(state.Axes[0]), Deadzone.Apply(state.Axes[1])); if (_thumbsticks[0].X != thumbstick0.X || _thumbsticks[0].Y != thumbstick0.Y) { ThumbstickMoved?.Invoke ( this, thumbstick0 ); } _thumbsticks[0] = thumbstick0; // Right Thumbstick var thumbstick1 = new Thumbstick(1, Deadzone.Apply(state.Axes[2]), Deadzone.Apply(state.Axes[3])); if (_thumbsticks[1].X != thumbstick1.X || _thumbsticks[1].Y != thumbstick1.Y) { ThumbstickMoved?.Invoke ( this, thumbstick1 ); } _thumbsticks[1] = thumbstick1; // Left Trigger var trigger0 = new Trigger(0, Deadzone.Apply(state.Axes[4])); if (_triggers[0].Position != trigger0.Position) { TriggerMoved?.Invoke(this, trigger0); } _triggers[0] = trigger0; // Right Trigger var trigger1 = new Trigger(1, Deadzone.Apply(state.Axes[5])); if (_triggers[1].Position != trigger1.Position) { TriggerMoved?.Invoke(this, trigger1); } _triggers[1] = trigger1; }
private void RaiseConnectionStateChanged(ConnectionState state, Exception error = null) { OnConnectionChanged?.Invoke(this, new ConnectionChangedEventArgs(state, error)); }
public void ConnectionChanged(bool isConnectd) { OnConnectionChanged?.Invoke(this, isConnectd); }