private void WebSocket_OnClose(object sender, CloseEventArgs e) { OnConnectionLost?.Invoke(this, null); websocketResetEvent.Reset(); logger?.Invoke("Websocket connection closed, trying to reconnect in 5s", MessageGroup.Error); wsConnectionDelayTimer.Start(); }
public void SendRequest(string message) { if (this.Connected && !string.IsNullOrEmpty(message)) { byte[] buffer = UTF8Encoding.UTF8.GetBytes(message); try { var stream = mTcpClient.GetStream(); lock (stream) { stream.Write(buffer, 0, buffer.Length); stream.WriteByte(0); // every message ends with zero } } catch (Exception) { //Debug.Log("[SnipeTCPClient] SendRequest failed: " + e.Message); Disconnect(); if (OnConnectionLost != null) { OnConnectionLost.Invoke(); } } } }
private void device_Disconnected(object sender, DisconnectedEventArgs e) { Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { Detatch(); OnConnectionLost?.Invoke(this); MainWindow.Instance.ShowBalloon("Connection Lost", "Failed to communicate with controller. It may no longer be connected.", Hardcodet.Wpf.TaskbarNotification.BalloonIcon.Error); } )); }
private void Process_Exited(object sender, EventArgs e) { if (sender is Process process) { if (process.Id == FFXIVProcessId) { Disconnect(); OnConnectionLost?.Invoke(this, new EventArgs()); } } }
private bool AttemptReconnect() { if (_attemptingReconnect) { return(false); } if (IsAlive) { // no reconnect needed return(true); } _attemptingReconnect = true; var sleep = _connectionEstablished ? 10 + _random.Next(0, 20) : 0; Helpers.ConsolePrint("SOCKET", "Attempting reconnect in " + sleep + " seconds"); // More retries on first attempt var retries = _connectionEstablished ? 5 : 25; if (_connectionEstablished) { // Don't wait if no connection yet Thread.Sleep(sleep * 1000); } else { // Don't not wait again _connectionEstablished = true; } for (var i = 0; i < retries; i++) { try { _webSocket.Connect(); Thread.Sleep(100); if (IsAlive) { _attemptingReconnect = false; return(true); } } catch (Exception e) { Helpers.ConsolePrint("SOCKET", $"Error while attempting reconnect: {e}"); } Thread.Sleep(1000); } _attemptingReconnect = false; OnConnectionLost?.Invoke(null, EventArgs.Empty); return(false); }
private async void WebSocket_OnClose(object sender, CloseEventArgs e) { if (!isConnectingNow) { disconnectionTime = DateTime.Now; isConnectingNow = true; } OnConnectionLost?.Invoke(this, null); websocketResetEvent.Reset(); logger.LogError("Websocket connection closed, trying to reconnect..."); await reconnectingDelayTask; ConnectWebSocket(); }
private void ReceiveLengthInt(IAsyncResult ar) { int dataLength = BitConverter.ToInt32(this._buffer); this._buffer = new byte[dataLength]; try { this._stream.BeginRead(this._buffer, 0, this._buffer.Length, new AsyncCallback(ReceiveData), null); }catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error with connection to the server."); OnConnectionLost.Invoke(); } }
private void WebSocket_OnClose(object sender, CloseEventArgs e) { logger.LogDebug("WebSocket_OnClose(): start"); preemptiveWebsocketReplacingTimer.Stop(); if (!isConnectingNow) { disconnectionTime = DateTime.Now; isConnectingNow = true; } logger.LogDebug("WebSocket_OnClose(): invoking OnConnectionLost"); OnConnectionLost?.Invoke(this, null); websocketResetEvent.Reset(); logger.LogError("Websocket connection closed, trying to reconnect..."); reconnectingDelayTask.Wait(); ConnectWebSocket(); }
private void ReceiveData(object?sender, DoWorkEventArgs args) { while (_client.Connected) { string?received; try { received = _reader.ReadLine(); } catch (Exception error) { if (_isConnectionLost) { break; } _isConnectionLost = true; OnConnectionLost?.Invoke(this, new ConnectionLostEventArgs { Reason = _isDisposed ? "Disconnected by user." : error.Message }); break; } if (string.IsNullOrEmpty(received)) { continue; } var parsed = ChatMessage.Parse(received); if (parsed.Command == ChatCommand.Disconnect) { if (_isConnectionLost) { break; } _isConnectionLost = true; OnConnectionLost?.Invoke(this, new ConnectionLostEventArgs { Reason = "Disconnected by user." }); break; } OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs { Message = parsed }); } }
//Получить свежие данные с сервера private void RefreshForecasts(bool handleConnecError = true) { try { ForecastsBlock = _forecastConnection.GetDataFromServer(); OnForecastUpdated?.Invoke(this, ForecastsBlock); } catch (ConnectionException e) { if (handleConnecError) { ExceptionLogger.Log(e); OnConnectionLost?.Invoke(this, e); _reconnectTimer.Start(); } else { throw; } } }
public TCPTransporter(string host, int port, string password, ILogger <TCPTransporter> logger) { tcpClient = new TcpClient(); tcpClient.ConnectAsync(host, port).Wait(); using (var writer = new BinaryWriter(tcpClient.GetStream(), Encoding.ASCII, true)) writer.Write(password); tasksSet.Add(Task.Factory.StartNew( async() => { try { await ReadStream(); } catch (Exception ex) { logger.LogWarning($"Connection was aborted, exception: {ex.Message}"); OnConnectionLost?.Invoke(); } })); this.logger = logger; }
public void SendCommand(byte[] msg) { long checksum = 0; foreach (byte b in msg) { checksum += b; } checksum &= 0xFF; byte[] msgWCS = new byte[msg.Length + 1]; Buffer.BlockCopy(msg, 0, msgWCS, 0, msg.Length); Buffer.SetByte(msgWCS, msg.Length, (byte)checksum); try { nwStream.Write(msgWCS, 0, msgWCS.Length); } catch (Exception) { ConnectionFailed = true; OnConnectionLost?.Invoke(this, null); } }
public void DropConnection() { dropConnectionSemaphore.Wait(); if (!connectionDroppedEventRaised) { try { stream?.Close(); stream?.Dispose(); keepAliveTimer?.Dispose(); keepAliveSemaphore?.Dispose(); OnConnectionLost?.Invoke(); connectionDroppedEventRaised = true; } catch (Exception e) { logger?.LogWarning(e, "Drop connection"); } finally { dropConnectionSemaphore.Release(); } } }
// Callback for Read operation private void ReadCallback(IAsyncResult result) { // ReadCallback is called asynchronously. That is why sometimes it could be called after disconnect and mTcpClient disposal. // Just ignoring and waiting for the next connection if (mTcpClient == null) { return; } NetworkStream network_stream; try { network_stream = mTcpClient.GetStream(); } #pragma warning disable CS0168 catch (Exception e) #pragma warning restore CS0168 { #if DEBUG Debug.Log("[SnipeTCPClient] ReadCallback GetStream error: " + e.Message); #endif Disconnect(); if (OnConnectionLost != null) { OnConnectionLost.Invoke(); } return; } byte[] buffer = result.AsyncState as byte[]; int bytes_read = 0; try { bytes_read = network_stream.EndRead(result); } #pragma warning disable CS0168 catch (Exception e) #pragma warning restore CS0168 { #if DEBUG Debug.Log("[SnipeTCPClient] ReadCallback stream.EndRead error: " + e.Message); #endif Disconnect(); if (OnConnectionLost != null) { OnConnectionLost.Invoke(); } return; } if (bytes_read > 0) { using (MemoryStream buf_stream = new MemoryStream(buffer, 0, bytes_read)) { try { ProcessData(buf_stream); } catch (Exception ex) { //#if DEBUG Debug.Log("[SnipeTCPClient] ProcessData error: " + ex.Message); //#endif } } } //Then start reading from the network again. network_stream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer); }
public void Response() { while (true) { try { byte[] receivebuffer = new byte[this.buffersize]; //this..Receive(receivebuffer, 0, receivebuffer.Length, 0); //string response = Encoding.ASCII.GetString(receivebuffer); StringBuilder messageData = new StringBuilder(); int bytes = -1; do { bytes = sslStream.Read(receivebuffer, 0, receivebuffer.Length); Decoder decoder = Encoding.UTF8.GetDecoder(); char[] messagepart = new char[decoder.GetCharCount(receivebuffer, 0, bytes)]; decoder.GetChars(receivebuffer, 0, bytes, messagepart, 0); messageData.Append(messagepart); if (messageData.ToString().IndexOf("<EOF>") != -1) { break; } } while (bytes != 0); string response = messageData.ToString(); response = response.Substring(0, response.Length - 5); Console.WriteLine(response); JObject obj = JObject.Parse(response); if (obj["action"] == null) { /* * Error shit * To do: * Write a file with the logs * Creating the MedicalProblems object * * */ Console.WriteLine("No action has been sent!"); return; } string action = (string)obj["action"]; switch (action) { case "response": MedicalProblems problem = new MedicalProblems(); Console.WriteLine("yes"); Console.WriteLine(obj["rezultat"][0][0].GetType()); Console.WriteLine(obj["rezultat"][1][1]); problem.Chanse_To_Have = obj["rezultat"][0][0].ToObject <double>(); problem.Chanse_To_Have_Nothing = obj["rezultat"][1][1].ToObject <double>(); //Console.WriteLine("Problem with invoke shit"); OnResponse?.Invoke(this, new OnReceiveMessageClientEventArgs { Medical = problem }); break; case "regresponse": Console.WriteLine("Receiving register response"); OnRegisterResponse?.Invoke(this, new OnReceiveRegisterMessageArgs { errorcode = (int)obj["errorcode"], errormessage = (string)obj["errormessage"] }); break; case "loginresponse": //Console.WriteLine("Receiving login response"); Console.WriteLine("Code..... \n"); string errorcodeestring = (string)obj["error"]; Console.WriteLine(errorcodeestring); int errorcodee = Int32.Parse(errorcodeestring); Console.WriteLine("Cod de eroare: " + errorcodee); if (errorcodee == 0) { this.Cookie = (string)obj["cookie"]; this.isloged = true; } OnLoginResponse?.Invoke(this, new OnReceiveLoginMessageArgs { errorcode = errorcodee, errormessage = (string)obj["errormessage"], username = (string)obj["username"] }); break; case "code_verify_response": Console.WriteLine("Receiving code_verify response"); OnCodeVerifyResponse?.Invoke(this, new OnCodeVerifyResponseArgs { errorcode = (int)obj["errorcode"], errormessage = (string)obj["errormessage"] }); break; case "results": int errorcode = (int)obj["error"]; if (errorcode == 0) { OnReceiveResultArgs args = JsonConvert.DeserializeObject <OnReceiveResultArgs>(response); OnReceiveResults?.Invoke(this, args); } else { } break; default: /* * Some error comming from server * or maybe from client? * IDK * * */ break; } } catch (Exception ex) { OnConnectionLost?.Invoke(this, EventArgs.Empty); Console.WriteLine("Wrong format " + ex.Message); this.isloged = false; break; } } }
private void UnderlyingSocket_ConnectionClosed() { OnConnectionLost?.Invoke(); }
void AgoraRtcEventHandler.OnConnectionLost() { OnConnectionLost?.Invoke(); }
private static void SocketOnOnConnectionLost(object sender, EventArgs eventArgs) { OnConnectionLost?.Invoke(sender, eventArgs); }
private void ConnectionLostDelegator() => OnConnectionLost?.Invoke();
public static void Bind() { Net.Init(); Net.On <S2C_HandshakeResponse>((header, connection, obj) => { if (!obj.OK) { connection.CloseConnection(false); } LocalPlayer = obj.LocalPlayer; //Now we're authed, so losing connection is fatal. connection.AppendShutdownHandler((c) => { Reset(); OnConnectionLost?.Invoke(c); }); OnHandshakeReceived?.Invoke(header, connection, obj); }); Net.On <S2C_InitialLobbyData>((header, connection, obj) => { OnInitialLobbyDataReceived?.Invoke(obj); }); Net.On <S2C_LobbyPlayerJoined>((header, connection, obj) => { OnLobbyPlayerJoined?.Invoke(obj); }); Net.On <S2C_LobbyPlayerLeft>((header, connection, obj) => { OnLobbyPlayerLeft?.Invoke(obj); }); Net.On <S2C_ServerPlayersOnlineCount>((header, connection, obj) => { OnServerPlayerCountChanged?.Invoke(obj); }); Net.On <S2C_SentPlayerInvite>((header, connection, obj) => { OnLobbyPlayerInviteSent?.Invoke(obj); }); Net.On <S2C_RevokedSentPlayerInvite>((header, connection, obj) => { OnLobbySentPlayerInviteRevoked?.Invoke(obj); }); Net.On <S2C_IncomingPlayerInvite>((header, connection, obj) => { OnLobbyPlayerInviteReceived?.Invoke(obj); }); Net.On <S2C_RevokedIncomingPlayerInvite>((header, connection, obj) => { OnLobbyIncomingPlayerInviteRevoked?.Invoke(obj); }); Net.On <S2C_InitNewGame>((header, connection, obj) => { OnInitNewGame?.Invoke(obj); }); Net.On <S2C_GameStarted>((header, connection, obj) => { OnGameStarted?.Invoke(obj); }); Net.On <S2C_GameTurnInfo>((header, connection, obj) => { OnGameTurnInfo?.Invoke(obj); }); Net.On <S2C_GameBoardUpdated>((header, connection, obj) => { OnGameBoardUpdated?.Invoke(obj); }); Net.On <S2C_GameEnded>((header, connection, obj) => { OnGameEnded?.Invoke(obj); }); }
private bool AttemptReconnect() { if (_attemptingReconnect || _endConnection) { return(false); } if (IsAlive) { // no reconnect needed return(true); } _attemptingReconnect = true; var sleep = _connectionEstablished ? 10 + _random.Next(0, 20) : 0; NHM.Common.Logger.Info("SOCKET", $"Attempting reconnect in {sleep} seconds"); // More retries on first attempt var retries = _connectionEstablished ? 5 : 25; if (_connectionEstablished) { // Don't wait if no connection yet Thread.Sleep(sleep * 1000); } else { // Don't not wait again _connectionEstablished = true; } for (var i = 0; i < retries; i++) { try { _webSocket.Connect(); Thread.Sleep(100); if (IsAlive) { _attemptingReconnect = false; return(true); } } catch (InvalidOperationException e) { if (e.Message == "A series of reconnecting has failed.") { // Need to recreate websocket NHM.Common.Logger.Info("SOCKET", "Recreating socket"); _webSocket = null; StartConnection(); break; } } catch (Exception e) { NHM.Common.Logger.Info("NiceHashSocket", $"Error while attempting reconnect: {e.Message}"); } Thread.Sleep(1000); } _attemptingReconnect = false; OnConnectionLost?.Invoke(null, EventArgs.Empty); return(false); }