public static void OpenTunnelPingListener() { if (TunnelValidatorRunning) { CloseTunnelPingListener(); } ServiceSettings serviceSettings = SettingsHelper.GetSettings(); if (TunnelHelper.CurrentTunnelStatus == TunnelStatuses.Started && serviceSettings.EnableTunnelValidation) { TunnelPingHelper.TunnelValidatorLastPingSuccessful = false; _validationListener = new TcpListener(IPAddress.Any, serviceSettings.TunnelValidationRemotePort); Task.Factory.StartNew(() => { TunnelPingHelper.TunnelValidatorRunning = true; _validationListener.Start(); try { while (true) { TcpClient tcpClient; try { tcpClient = _validationListener.AcceptTcpClient(); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.Interrupted) { TunnelPingHelper.TunnelValidatorRunning = false; break; } else { throw; } } Task.Factory.StartNew(() => { try { NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[32]; string validationString = ""; while (true) { int bytesRead = clientStream.Read(message, 0, 32); if (bytesRead == 0) { break; } ASCIIEncoding encoding = new ASCIIEncoding(); string str = encoding.GetString(message, 0, bytesRead); validationString += str; if (validationString == "-111-") { const string sendString = "-222-"; byte[] sendData = Encoding.ASCII.GetBytes(sendString); clientStream.Write(sendData, 0, sendData.Length); break; } else if (validationString.Length > 5) { break; } } tcpClient.Close(); } catch (Exception ex) { WcfServerHelper.BroadcastRemoteCallback((x) => x.EventToLog("Tunnel Validation Exception (1): " + ex.Message + " ::: " + ex.StackTrace, DateTime.Now)); HandleFailedTunnelPing(); } }); } } catch (Exception ex) { WcfServerHelper.BroadcastRemoteCallback((x) => x.EventToLog("Tunnel Validation Exception (2): " + ex.Message + " ::: " + ex.StackTrace, DateTime.Now)); HandleFailedTunnelPing(); } }, TaskCreationOptions.LongRunning); _pingTunnelTimer = new System.Timers.Timer(); _pingTunnelTimer.Interval = serviceSettings.TunnelValidationPingInterval * 1000; _pingTunnelTimer.AutoReset = true; _pingTunnelTimer.Elapsed += _pingTunnelTimer_Elapsed; Thread.Sleep(1200); SendTunnelPing(); _pingTunnelTimer.Start(); } }