public override void OnReceive(Android.Content.Context context, Android.Content.Intent intent) { try { string action = intent.Action; switch (action) { case BluetoothDevice.ActionAclConnected: case BluetoothDevice.ActionAclDisconnected: { BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice); if (device != null) { if (!string.IsNullOrEmpty(_connectDeviceAddress) && string.Compare(device.Address, _connectDeviceAddress, StringComparison.OrdinalIgnoreCase) == 0) { _deviceConnected = action == BluetoothDevice.ActionAclConnected; ConnectedEvent.Set(); } } break; } } } catch (Exception) { // ignored } }
void HandleConnectedEvent() { if (ConnectedEvent != null) { ConnectedEvent.Invoke(); } }
/// <summary> /// Raised by the underlying <see cref="Connection"/> when a connection is established /// </summary> private void Connection_ConnectedEvent(object sender, EventArgs e) { // Just pass on the event along var args = new object[] { sender, e }; ConnectedEvent.RaiseEventSafe(ref args); }
public LatencyViewModel() { var mapper = Mappers.Xy <LatencyModel>() .X(model => model.DateTime.Ticks) .Y(model => model.Value); Charting.For <LatencyModel>(mapper); ChartValues = new ChartValues <LatencyModel>(); DateTimeFormatter = value => new DateTime((long)value).ToString("mm:ss"); CpuFormatter = value => String.Format("{0}%", value.ToString()); AxisStep = TimeSpan.FromSeconds(1).Ticks; AxisUnit = TimeSpan.TicksPerSecond; SetAxisLimits(DateTime.Now); IsReading = false; // 新建一个进程获取网络监控信息 IsReading = !IsReading; // start a task with a means to do a hard abort (unsafe!) Cts = new CancellationTokenSource(); Ct = Cts.Token; if (IsReading) { Task.Factory.StartNew(Read, Ct); } //获取事件聚合器, 连接成功时开始监控 eventAggregator = ServiceLocator.Current.GetInstance <IEventAggregator>(); ConnectedEvent e = eventAggregator.GetEvent <ConnectedEvent>(); e.Subscribe(GetConfig, ThreadOption.UIThread); }
protected override void OnHandshaked() { Log.Information("Connected to service."); _connectedPrev = true; ConnectedEvent?.Invoke(this, EventArgs.Empty); }
/// <summary> /// Connects the session to the given multicast group (IP address). /// </summary> /// <param name="group">The multicast group to join.</param> /// <param name="port">The port to connect to.</param> /// <param name="ttl">The multicast time to live (TTL).</param> public async Task ConnectMulticastAsync(IPAddress group, int port, int ttl) { // TODO: disconnect first? Logger.Info($"Session {Id} connecting to multicast group {group}:{port}..."); try { _socketConnecting = true; _socket = await NetUtil.ConnectMulticastAsync(group, port, ttl).ConfigureAwait(false); if (null == _socket) { await ErrorAsync($"Could not connect to multicast group {group}:{port}!").ConfigureAwait(false); return; } } finally { _socketConnecting = false; } if (IsConnected) { ConnectedEvent?.Invoke(this, new ConnectedEventArgs()); } else { // TODO: error? } }
/// <inheritdoc /> public virtual void OnConnected(IPlugin plugin) { Plugin = plugin; Status = PluginStatus.Connected; ConnectedEvent.Set(); }
/// <summary> /// Connects to the Parrot RF Service, if that succeeds /// it starts waiting for data to handle. /// /// Throws an exception when the connection failed. /// </summary> public async Task ConnectAsync() { // Find the Parrot RF Service. var parrotService = Device.InstalledServices.FirstOrDefault(x => ParrotRfServiceGuids.Contains(x)); if (parrotService == null) { throw new Exception("Couldn't find the parrot rf service."); } // Connect to the service. BluetoothClient.Connect(Device.DeviceAddress, parrotService); if (!BluetoothClient.Connected) { throw new Exception("Couldn't connect to the parrot rf service."); } // Send initial packet and stop other packets from being sent. var initialPacket = new byte[] { 0x00, 0x03, 0x00 }; await BluetoothClient.GetStream().WriteAsync(initialPacket, 0, initialPacket.Length); await BluetoothClient.GetStream().FlushAsync(); await BluetoothClient.GetStream().ReadAsync(new byte[3], 0, 3); // Dispatch event ConnectedEvent.AsyncSafeInvoke(this, EventArgs.Empty); }
void HandleConnectedEvent(IConnection conn) { if (ConnectedEvent != null) { ConnectedEvent.Invoke(conn); } }
public static void ConnectedPriority([NotNull] EventHandler <PlayerConnectedEventArgs> callback, Priority priority) { if (callback == null) { throw new ArgumentNullException("callback"); } ConnectedEvent.Add(callback, priority); }
public Guid OnStarting() { Status = PluginStatus.Starting; ConnectedEvent.Reset(); return(Guid = Guid.NewGuid()); }
void HandleConnectEvent() { m_State = ConnectState.Connected; m_Connection.IsConnected = true; ConnectedEvent?.Invoke(); }
/// <summary> /// Raised by the socket wrapper when a connection is successfully made /// </summary> private void ClientInstance_ConnectedEvent(object sender, EventArgs e) { Logger.Log(Logger.Level.Info, "Connection to the server made successfully. Passing on...."); // Pass the event on var args = new object[] { sender, e }; ConnectedEvent.RaiseEventSafe(ref args); }
/// <param name="crashed"></param> /// <inheritdoc /> public virtual void OnStopped(bool crashed) { Process = null; Plugin = default; Guid = default; Status = PluginStatus.Stopped; ConnectedEvent.Set(); }
/// <inheritdoc /> public virtual Guid OnStarting() { Guid = Guid.NewGuid(); Status = PluginStatus.Starting; ConnectedEvent.Reset(); return(Guid); }
public void OnStopped() { ConnectedEvent.Set(); Status = PluginStatus.Stopped; Process = null; Plugin = null; Guid = default; }
protected virtual void OnConnected() { if (!IsConnected) { IsConnected = true; ConnectedEvent.Set(); Connected?.Invoke(this, null); } }
private void OnConnectedToGameServer(ConnectedEvent eve) { SetAndReportStatus(ShamanClientStatus.AuthorizingGameServer, _statusCallback); //authorizing matchmaker SendShamanRequest <AuthorizationResponse>(new AuthorizationRequest { SessionId = SessionId }, OnGameAuthorizationResponse); }
private async Task HandleConnection(CancellationTokenSource connectionCts) { Interlocked.Exchange(ref _hbLastAction, 0); using (_client = new ClientWebSocket()) { try { _ = Task.Run(() => HeartbeatWatcher(_client, connectionCts)); await _client.ConnectAsync(new Uri(_url), connectionCts.Token); ConnectedTime = DateTime.UtcNow; ConnectedEvent.Set(); ConnectedEvent.Reset(); Interlocked.Exchange(ref _hbLastAction, 0); var currentHello = HelloMessage; var helloAs = new ArraySegment <byte>(JsonSerializer.Serialize(currentHello)); await _client.SendAsync(helloAs, WebSocketMessageType.Text, true, connectionCts.Token); Interlocked.Exchange(ref _hbLastAction, 0); var bufferArray = new byte[ReceiveBufferSize]; while (_client.State == WebSocketState.Open && !connectionCts.IsCancellationRequested) { if (currentHello != HelloMessage) { currentHello = HelloMessage; helloAs = new ArraySegment <byte>(JsonSerializer.Serialize(currentHello)); await _client.SendAsync(helloAs, WebSocketMessageType.Text, true, connectionCts.Token); Interlocked.Exchange(ref _hbLastAction, 0); } var messageData = await WSUtils.ReceiveMessage(_client, connectionCts.Token, bufferArray); Interlocked.Exchange(ref _hbLastAction, 0); if (messageData.MessageType == WebSocketMessageType.Close) { return; } _queueThread.Enqueue(messageData); } } catch (TaskCanceledException) { await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal", CancellationToken.None); } catch (Exception ex) { OnError(ex); } } }
void HandleConnectEvent() { m_State = ConnectState.Connected; m_Connection.IsConnected = true; if (ConnectedEvent != null) { ConnectedEvent.Invoke(); } }
public void OnConnected(ISMAPlugin plugin) { Status = PluginStatus.Connected; Plugin = plugin; if (Metadata.IsDevelopment) { Metadata.DisplayName = plugin.Name; } ConnectedEvent.Set(); }
void HandleConnect(int connectionId, NetworkError error) { var connection = new Connection(m_SocketId, connectionId, true, error); // add connection at correct index while (m_Connections.Count <= connectionId) { m_Connections.Add(null); } m_Connections[connectionId] = connection; ConnectedEvent?.Invoke(connection); }
private async Task HandleConnection(CancellationTokenSource connectionCts) { _hbLastAction = DateTime.UtcNow; using (_client = new ClientWebSocket()) { try { _ = Task.Run(() => HeartbeatWatcher(_client, connectionCts)); await _client.ConnectAsync(new Uri(_url), connectionCts.Token); ConnectedEvent.Set(); ConnectedEvent.Reset(); _hbLastAction = DateTime.UtcNow; var currentHello = HelloMessage; var helloAs = new ArraySegment <byte>(JsonSerializer.Serialize(currentHello)); await _client.SendAsync(helloAs, WebSocketMessageType.Text, true, connectionCts.Token); _hbLastAction = DateTime.UtcNow; while (_client.State == WebSocketState.Open && !connectionCts.IsCancellationRequested) { if (currentHello != HelloMessage) { currentHello = HelloMessage; helloAs = new ArraySegment <byte>(JsonSerializer.Serialize(currentHello)); await _client.SendAsync(helloAs, WebSocketMessageType.Text, true, connectionCts.Token); _hbLastAction = DateTime.UtcNow; } var messageData = await WSUtils.ReceiveMessage(_client, connectionCts.Token); _hbLastAction = DateTime.UtcNow; if (messageData.MessageType == WebSocketMessageType.Close) { return; } _queueThread.Enqueue(messageData); } } catch (TaskCanceledException) { } catch (Exception ex) { OnError(ex); } } }
protected void OnConnected() { retryCount = 0; isConnecting = false; if (connection != null) { connection.MessageRespondEvent -= OnMessageRespond; connection.MessageRespondEvent += OnMessageRespond; } ConnectedEvent?.Invoke(); InvokeStatusEvent(NetworkStatus.Connected); prevHeartbeatDateTime = DateTime.Now; StopAllCoroutines(); connectCor = StartCoroutine(ConnectionDetectAsync()); heartbeatCor = StartCoroutine(HeartbeatDetectAsync()); }
public async Task ConnectAsync() { try { await _connection.StartAsync(); NotifyNewLogMessageEvent($"Connected to hub: {Endpoint}"); IsConnected = true; ConnectedEvent?.Invoke(); } catch (Exception ex) { NotifyNewLogMessageEvent($"Something went wrong while connecting to {Endpoint}: {ex.Message}"); IsConnected = false; Task.Delay(30000).Wait(); await ConnectAsync(); } }
protected void ConnectMethod() { try { CloseActiveConnection(); _client = new TcpClient(); while (!Terminated && !ConnectToTCPServer()) { Thread.Sleep(ReconnectInterval); } if (!Terminated) { _netStream = _client.GetStream(); _netStream.ReadTimeout = _readTimeOut; _netStream.WriteTimeout = _writeTimeOut; if (_receivedDataAsync != null) { // subscribe for receiving messages _netStream.BeginRead(_readBuffer, 0, _readBuffer.Length, EndRead, _readBuffer); } WorkWithSync(() => { ConnectionStatus = ConnectionStatusEnum.ConnectedNotInicialized; }); if (_inicializationMethod() == true) { WorkWithSync(() => { ConnectionStatus = ConnectionStatusEnum.ConnectedInicialized; ConnectedEvent.Set(); }); } } } catch (Exception) { throw; } }
/// <summary> /// 运行aap服务器 /// </summary> /// <param name="app"></param> public void StartApp(ConnectedEvent app) { AppServer.Start(); App = new Thread(() => { while (true) { try { var v = AppServer.GetContext(); app?.Invoke(v); } catch (Exception ex) { ThreadMsgEvent?.BeginInvoke(ex.StackTrace, null, null); } } }); App.Start(); }
public static void AcceptCallback(IAsyncResult ar) { Debug.WriteLine("AcceptCallback"); // Get the socket that handles the client request. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.listenSocket; Socket newSocket = handler.EndAccept(ar); // Create the state object. state.workSocket = newSocket; // Start reading data StartReadPacket(state); // Notify a new person connected var e = new ConnectedEventArgs(); ConnectedEvent.Invoke(null, e); }
protected bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { OnDisconnect("Ipc object disposed"); if (dedicatedWriteThread) { writeTaskCancel.Cancel(); } readStream?.Dispose(); writeStream.Dispose(); readBuffer = null; ConnectedEvent?.Dispose(); } disposedValue = true; } }
/// <summary> /// 运行图像上传服务器 /// </summary> /// <param name="img"></param> public void StartImg(ConnectedEvent img) { ImgServer.Start(); Img = new Thread(() => { while (true) { Sem2.WaitOne(); try { var v = ImgServer.GetContext(); img?.Invoke(v); } catch (Exception ex) { ThreadMsgEvent?.BeginInvoke(ex.StackTrace, null, null); } Sem2.Release(); } }); Img.Start(); }