public virtual bool OnDisconnect() { ConnectionLost?.Invoke(); CloseSocket(); return(true); }
public void Receive(int bufferSize = 128) { if (Stream == null || !_socket.Connected) { return; } Task.Run( // Initiate the receiver thread () => { bool error = false; do { if (!TryReceiveOnce(out Packet packet)) { error = true; ConnectionLost?.Invoke(this, null); } if (packet != null) { packet.ParseFailed += PacketParseFailed; } DataReceived?.Invoke(this, packet); } while (_socket.Connected && !error); } ); }
public AccDataConnection(string host, int port, string password, TimeSpan?updateInterval) { _host = host; _port = port; _password = password; _updateInterval = updateInterval.GetValueOrDefault(_defaultUpdateInterval); _client = new UdpClient(); _cancellationTokenSource = new CancellationTokenSource(); _cancellationToken = _cancellationTokenSource.Token; _noMessagesReceivedTimer = new Timer(); _noMessagesReceivedTimer.Elapsed += (_, __) => { if (_registered && !_sendingPing) { SendPing(); _sendingPing = true; return; } if (_registered) { ConnectionLost?.Invoke(null, new ConnectionLostEventArgs()); } _registered = false; Connected = false; SendRegistrationRequest(); }; }
public ServiceClient(IClientLogic logic, IPAddress hostIP, int port, int interfaceId, long ticket) { this.logic = logic; client = new DynamicClient(hostIP, port); tree = new ProtocolTree(); root = new DummyHandler <DummyProtocol>(); auth = new LeafProtocolHandler <AuthenticationProtocol>(); tree.Register(root); tree.Register(auth); tree.Entry(root); tree.ConnectToLeaf(root, auth); tree.Connect(root, logic.ProtocolTree); app = new ApplicationConnectionManager(client, tree, 3000, 6000); auth.NewData += data => { switch (data.statusCode) { case AuthenticationProtocol.StatusCode.Request: Logger.Log("receiving auth request", "ServiceClient"); auth.Send(new AuthenticationProtocol { interfaceId = interfaceId, ticket = ticket, resumeToken = ResumeToken, statusCode = AuthenticationProtocol.StatusCode.Ack }); break; case AuthenticationProtocol.StatusCode.Accept: Logger.Log("auth accepted by the host", "ServiceClient"); ResumeToken = data.resumeToken; ConnectionAccepted?.Invoke(); break; case AuthenticationProtocol.StatusCode.Reject: Logger.Log($"auth rejected by the host, {data.reason}", "ServiceClient", Logger.LogType.WARNING); rejected = true; client.CloseConnection(); app.Dispose(); ConnectionRejected?.Invoke(); break; default: Logger.Log("invalid auth msg from host", "ServiceClient", Logger.LogType.WARNING); break; } }; app.ConnectionLost += () => { if (!rejected) { ConnectionLost?.Invoke(); } }; }
public void Run() { Task.Run(() => { while (!cancellationToken.IsCancellationRequested) { double noResponseTime = (DateTime.UtcNow - lastHeartbeatTimeProvider()).TotalSeconds; if (noResponseTime > ConnectionTimeoutInSeconds) { ConnectionLost?.Invoke(); break; } else if (noResponseTime > NeedRefreshTimeoutInSeconds) { if ((DateTime.UtcNow - lastRefreshRequestTime).TotalSeconds >= 1.0) { lastRefreshRequestTime = DateTime.UtcNow; DataRefreshNeeded?.Invoke(); } } Thread.Sleep(checkDelay); } }); }
/// <summary> /// Receives data from network stream and processes it. /// </summary> private void ReceiveData() { try { NetworkStream stream = connection.GetStream(); byte[] buffer = new byte[256]; for (int bytesRead; (bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0;) { string data = Encoding.UTF8.GetString(buffer, 0, bytesRead); DataProcessor.Process(data); } } catch (IOException) { ConnectionLost?.Invoke(this, EventArgs.Empty); } catch (ObjectDisposedException) { ConnectionLost?.Invoke(this, EventArgs.Empty); } catch (InvalidOperationException) { ConnectionLost?.Invoke(this, EventArgs.Empty); } }
/// <summary> /// Начать обработку входящих сообщений клиента. /// </summary> public void Process() { try { _stream = _client.GetStream(); var initialMessage = (Message)_formatter.Deserialize(_stream); UserName = initialMessage.Text; var eventArgs = new MessageEventArgs { Message = initialMessage }; NewUser?.Invoke(this, eventArgs); while (true) { var message = (Message)_formatter.Deserialize(_stream); eventArgs = new MessageEventArgs { Message = message }; NewMessage?.Invoke(this, eventArgs); } } catch (Exception e) { var eventArgs = new ErrorEventArgs(e); ConnectionLost?.Invoke(this, eventArgs); } finally { Dispose(); } }
protected virtual void OnDisconnect(bool expected, bool forceEventFire = false) { bool wasConnected = State == ConnectionState.Connected; _state = ConnectionState.Disconnected; // else: ApplyReconnectBehavior will set it to Connecting // if state wasn't already "Disconnected", fire event if (wasConnected || forceEventFire || AlwaysFireConnectionFailed) { ConnectionLost?.Invoke(this, new ConnectionLostArgs( expected ? ReconnectBehavior.Ignore : ReconnectBehavior, null)); } if (!expected) { Cleanup(); // enforce a proper disconnect ApplyReconnectBehavior(); } else { // make sure pending reconnects are skipped _abortReconnect = true; } }
private void SocketClosed() { log.Write(LogVerbosity.Info, "Socket closed"); Closed?.Invoke(); authenticated = false; var shouldReconnect = false; if (!reconnecting) { lock (registrationLock) if (registrations.Any()) { shouldReconnect = true; } } if (!shouldReconnect) { return; } reconnecting = true; ConnectionLost?.Invoke(); Task.Run(() => TryReconnect()); }
public virtual void EventDisconnect(object objResponse) { ConnectionLost?.Invoke(); ErrorMessage = new Exception(objResponse.ToString()); Debug.WriteLine("EventDisconnect == " + objResponse); }
void INotificationHandler.HandleResponse(IQueryClient queryClient, string responseText) { CommandParameterGroupList parameterGroupList = CommandParameterGroupList.Parse(responseText); int?reasonId = parameterGroupList.GetParameterValue <int?>("reasonid") ?? (int)ClientLeftReason.Disconnect; switch ((ClientLeftReason)reasonId.Value) { case ClientLeftReason.Kicked: Kicked?.Invoke(queryClient, new ClientKickEventArgs(parameterGroupList)); break; case ClientLeftReason.Banned: Banned?.Invoke(queryClient, new ClientBanEventArgs(parameterGroupList)); break; case ClientLeftReason.ConnectionLost: ConnectionLost?.Invoke(queryClient, new ClientConnectionLostEventArgs(parameterGroupList)); break; case ClientLeftReason.Disconnect: Disconnected?.Invoke(queryClient, new ClientDisconnectEventArgs(parameterGroupList)); break; } }
// Keep server connection alive by pinging private async void KeepAlive() { while (true) { await Task.Delay(PingDelay).ConfigureAwait(false); bool isAlive = Socket.Ping(); // Try to ping the server if (isAlive) { continue; // Client responded, continue pinger } // ---- Socket is NOT alive: ---- // ConnectionLost?.Invoke(EndPoint); // Client does not respond, try reconnecting, or disconnect & exit if (AutoReconnect) { await Reconnect().ConfigureAwait(false); // Wait for reconnect } else { Disconnect(); // Stop and exit return; } } }
public CommunicationManager() { /*if (Instance == null) * Instance = this; * else * throw new Exception();*/ connection = new HubConnectionBuilder() .WithUrl(SERVER_URL + "/gamehub") .Build(); connection.Closed += async(error) => { connected = false; if (ConnectionLost != null) { ConnectionLost.Invoke(); } Logger.Log("CONNECTION LOST"); await Task.Delay(new Random().Next(0, 5) * 1000); await connection.StartAsync(); }; connection.Reconnected += async(connectionId) => { connected = true; Logger.Log("RECONNECTED"); }; }
/// <summary> /// New socket connection /// </summary> /// <param name="client">The socket client</param> /// <param name="socket">The socket</param> public SocketConnection(SocketClient client, IWebsocket socket) { log = client.log; socketClient = client; pendingRequests = new List <PendingRequest>(); handlers = new List <SocketSubscription>(); Socket = socket; Socket.Timeout = client.SocketNoDataTimeout; Socket.OnMessage += ProcessMessage; Socket.OnClose += () => { if (lostTriggered) { return; } DisconnectTime = DateTime.UtcNow; lostTriggered = true; if (ShouldReconnect) { ConnectionLost?.Invoke(); } }; Socket.OnClose += SocketOnClose; Socket.OnOpen += () => { PausedActivity = false; Connected = true; }; }
private void CloseAndRaise() { CloseConnection(); Log("invoking connection lost"); ConnectionLost?.Invoke(); Log("invoking connection lost, done"); }
internal void OnConnectionLost() { if (isDisposed) { return; } ConnectionLost?.Invoke(); }
protected virtual void OnConnectionLost() { // DEBUG: Log connection lost. Log.Debug($"Connection to ('{_address}:{_port}') was lost."); ConnectionState = ClientConnectionState.Disconnected; ConnectionLost?.Invoke(this, new EventArgs()); }
private void Handler_HasCome(object sender, Message msg) { _toServiceMessenger = Utils.GetAnswerMessenger(msg); switch ((ServiceOperation)msg.What) { case ServiceOperation.GetClientSettings: _callbacks.Dequeue(ServiceOperation.GetClientSettings, Utils.GetData <ConnectionCredentials>(msg)); break; case ServiceOperation.GetIsConnected: _callbacks.Dequeue(ServiceOperation.GetIsConnected, Utils.GetData <ManagerConnectionState>(msg)); break; case ServiceOperation.GetScenarios: _callbacks.Dequeue(ServiceOperation.GetScenarios, Utils.GetData <ScenarioInfo[]>(msg)); break; case ServiceOperation.GetNotifications: _callbacks.Dequeue(ServiceOperation.GetNotifications, Utils.GetData <LazuriteNotification[]>(msg)); break; case ServiceOperation.ConnectionLost: ConnectionLost?.Invoke(); break; case ServiceOperation.ConnectionRestored: ConnectionRestored?.Invoke(); break; case ServiceOperation.CredentialsInvalid: LoginOrPasswordInvalid?.Invoke(); break; case ServiceOperation.CredentialsLoaded: CredentialsLoaded?.Invoke(); break; case ServiceOperation.NeedClientSettings: NeedClientSettings?.Invoke(); break; case ServiceOperation.NeedRefresh: NeedRefresh?.Invoke(); break; case ServiceOperation.ScenariosChanged: ScenariosChanged?.Invoke(Utils.GetData <ScenarioInfo[]>(msg)); break; case ServiceOperation.SecretCodeInvalid: SecretCodeInvalid?.Invoke(); break; case ServiceOperation.ConnectionError: ConnectionError?.Invoke(); break; } }
private bool HandleExceptions(Action action) { var cancellationToken = _operationCancellationTokenSource.Token; bool success = false; try { if (_credentials != null && (_serviceClient?.IsClosedOrFaulted ?? false)) { _serviceClient = ClientsManager.Create(_credentials.Value); } if (ConnectionState == ManagerConnectionState.Disconnected) { ConnectionState = ManagerConnectionState.Connecting; } action(); success = true; if (ConnectionState != ManagerConnectionState.Connected) { ConnectionState = ManagerConnectionState.Connected; ConnectionRestored?.Invoke(); } } catch (System.Exception e) { if (!cancellationToken.IsCancellationRequested) { if (SystemUtils.IsFaultExceptionHasCode(e, ServiceFaultCodes.AccessDenied)) { LoginOrPasswordInvalid?.Invoke(); } //if data is wrong or secretKey.Length is wrong else if ( SystemUtils.IsFaultExceptionHasCode(e, ServiceFaultCodes.DecryptionError) || e is SerializationException || e is DecryptException || e.Message == "Key length not 128/192/256 bits.") { SecretCodeInvalid?.Invoke(); } else if (ConnectionState != ManagerConnectionState.Connected) { ConnectionLost?.Invoke(); } else { ConnectionError?.Invoke(); } ConnectionState = ManagerConnectionState.Disconnected; success = false; } } if (cancellationToken.IsCancellationRequested) { return(false); } return(success); }
private void OnDeviceConnectionLost(object sender, DeviceErrorEventArgs e) { if (_device.Equals(e.Device)) { Debug.WriteLine("Device connection lost!"); _characteristics.Clear(); ConnectionLost.Invoke(this, null); } }
public DynamicEndpoint(dynamic client) { this.client = client; ITransportationLayer transport = client; transport.ConnectionEstablished += () => ConnectionEstablished?.Invoke(); transport.ConnectionLost += () => ConnectionLost?.Invoke(); transport.ProviderDataReady += data => ProviderDataReady?.Invoke(data); }
public async Task Send(T message) { if (message.Equals(default(T))) { throw new ArgumentNullException(nameof(message)); } bool alive = Socket.Ping(); if (!alive) { throw new TransferException($"The Socket to {EndPoint} is not responding!"); } try { // build byte[] out of message (serialize with ZeroFormatter) var bytes = ZeroFormatterSerializer.Serialize(message); var segment = new ArraySegment <byte>(bytes); int size = bytes.Length; await LeadingByteProcessor.SendLeading(Socket, size) .ConfigureAwait(false); // Send receiver the byte count //TODO: Decide whether to catch errors in buffer-loop and continue once fixed or cancel whole send? int written = 0; while (written < size) { int send = size - written; // current buffer size if (send > SendBufferSize) { send = SendBufferSize; // max size } var slice = segment.SliceEx(written, send); // buffered portion of array written = await Socket.SendAsync(slice, SocketFlags.None).ConfigureAwait(false); } if (written < 1) { throw new TransferException($"{written} bytes were sent! " + "Null bytes could mean a connection shutdown."); } } catch (SocketException) { ConnectionLost?.Invoke(EndPoint); // On any error - cancel whole buffered writing if (AutoReconnect) { await Reconnect().ConfigureAwait(false); // Try reconnecting and re-send everything once reconnected } else { throw; // Throw if we're not trying to reconnect } } }
private void SocketClosed() { log.Write(LogVerbosity.Debug, "Socket closed"); if (!reconnecting && registrations.Any()) { reconnecting = true; ConnectionLost?.Invoke(); Task.Run(() => TryReconnect()); } }
public void Close(bool invokeConnectionLostEvent) { if (_socket.Connected && invokeConnectionLostEvent) { ConnectionLost?.Invoke(this, null); } _socket.Close(); Stream?.Close(); }
private void onConnectionLost() { if (!isConnected()) { Debug.Assert(false); return; } startConnectionCheckingTimer(); Trace.TraceInformation("[GitLabInstance] Connection lost ({0})", HostName); ConnectionLost?.Invoke(); }
private void OnConnectionLost() { // In order to play nicely with WinForms controls, we do a check here to // see if it is necessary to synchronize this event with the UI thread. // if (!(ConnectionLost?.Target is Control)) return; // var target = (Control) ConnectionLost.Target; // // if (target != null) // target.Invoke(ConnectionLost, this, EventArgs.Empty); // else ConnectionLost?.Invoke(this, EventArgs.Empty); }
private void OnDisconnected(object sender, DisconnectedEventArgs e) { var removed = _peripherals.Remove(e.Connection, out var peripheral); if (!removed || e.Reason == 0x0216) // We didn't hold the connection or disconnected by central. { return; } var eventArgs = new PeripheralEventArgs(peripheral); ConnectionLost?.Invoke(this, eventArgs); }
private void ExceptionFreeAction(Action action, [CallerMemberName] string actionName = null) { try { action(); LastActionToServer = DateTime.Now; } catch (Exception ex) { Log.Default.WriteLine(LogLevels.Error, "Exception:{0} {1}", actionName, ex); ConnectionLost?.Invoke(); _factory?.Abort(); } }
/// <summary> /// Send a set command to the connected switch /// </summary> /// <param name="pinNumber">The pin to set</param> /// <param name="state">The state to set the pin to, either high or low</param> public void SetPinState(byte pinNumber, byte state) { if (stream == null) { ConnectionLost?.Invoke(this, EventArgs.Empty); } try { var data = new[] { CmdSet, pinNumber, state }; stream?.Write(data, 0, 3); } catch (Exception e) { ConnectionLost?.Invoke(this, EventArgs.Empty); } }
private ApplicationConnectionManager(ITransportationLayer transportationLayer, ProtocolTree protocolTree, FTConnectionController ft) : this(transportationLayer) { this.ft = ft; tree.Register(ft); tree.Entry(ft); tree.Connect(ft, protocolTree); ft.ConnectionLost += () => { CloseConnectionAndCleanUp(); ConnectionLost?.Invoke(); }; }