コード例 #1
0
        public static void PlatformSpecificDispose(WaitHandle wh)
        {
#if DOTNETSTANDARD_1_3
            wh?.Dispose();
#else
            wh?.Close();
#endif
        }
コード例 #2
0
 /// <summary>
 /// 释放资源。
 /// </summary>
 public void Dispose()
 {
     using (WaitHandle)
     {
         if (WaitHandle != null)
         {
             if (!(WaitHandle?.SafeWaitHandle?.IsClosed).GetValueOrDefault(true))
             {
                 WaitHandle?.Close();
             }
         }
     }
     WaitHandle = null;
 }
コード例 #3
0
        public static bool ValidIPEndPoint(IPEndPoint e, double waittime = 0.05)
        {
            using (TcpClient tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(e.Address, e.Port, null, null);
                WaitHandle   wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(waittime), false))
                    {
                        tcp.Close();
                        return(false);
                    }

                    tcp.EndConnect(ar);
                    return(true);
                }
                finally
                {
                    wh.Close();
                }
            }
        }
コード例 #4
0
        public BluetoothClientWrapper Connect(BluetoothDeviceInfo device, string DEVICE_PIN)
        {
            // check if device is paired
            if (device.Authenticated)
            {
                bool connectSuccess = false;
                // set pin of device to connect with
                localClient.SetPin(DEVICE_PIN);
                // async connection method
                //localClient.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), device);

                IAsyncResult ar = localClient.BeginConnect(localClient.RemoteEndPoint as BluetoothEndPoint, null, device);

                WaitHandle connectionWait = ar.AsyncWaitHandle;
                try {
                    if (!ar.AsyncWaitHandle.WaitOne(5000, false))
                    {
                        localClient.Close();
                        connectSuccess = false;
                    }

                    localClient.EndConnect(ar);
                }
                finally {
                    connectionWait.Close();
                }

                if (!connectSuccess)
                {
                    throw new Exception("Timeout waiting for remoteEndPoint to accept bluetooth connection.");
                }

                return(new BluetoothClientWrapper(localClient));
                //return Task<BluetoothClientWrapper>.Factory.FromAsync(localClient.BeginConnect, Connect, device.DeviceAddress, BluetoothService.SerialPort, device);
            }
            throw new Exception("Not Authenticated!");
        }
コード例 #5
0
ファイル: WeChatLink.cs プロジェクト: TonyDongGuaPi/joework
 private void AsynRecive(Socket socket)
 {
     Debug.Log(string.Empty);
     WeChatLink.StateObject stateObject = new WeChatLink.StateObject();
     stateObject.workSocket = socket;
     try
     {
         IAsyncResult asyncResult     = socket.BeginReceive(stateObject.buffer, 0, 1024, 0, null, stateObject);
         WaitHandle   asyncWaitHandle = asyncResult.get_AsyncWaitHandle();
         try
         {
             if (!asyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds((double)this.sendRcvTimeOut)))
             {
                 Debug.Log("Receive Time Out:" + this.sendRcvTimeOut.ToString());
                 this.CloseSocket(socket);
             }
             else
             {
                 this.ReceiveCallback(asyncResult);
             }
         }
         catch (Exception ex)
         {
             Debug.Log(ex.get_Message());
             this.CloseSocket(socket);
         }
         finally
         {
             asyncWaitHandle.Close();
         }
     }
     catch (Exception ex2)
     {
         Debug.Log(ex2.get_Message());
         this.CloseSocket(socket);
     }
 }
コード例 #6
0
        public void Dispose()
        {
            if (_waitHandle == null)
            {
                return;
            }

            if (_hasHandle && _waitHandle is Mutex)
            {
                ((Mutex)_waitHandle).ReleaseMutex();
#if NETSTANDARD
                _waitHandle.Dispose();
#else
                _waitHandle.Close();
#endif
            }

            if (_hasHandle && _waitHandle is AutoResetEvent)
            {
                ((AutoResetEvent)_waitHandle).Set();
            }

            _waitHandle = null;
        }
コード例 #7
0
        public void MessageSendThread()
        {
            while (!_cancel.IsCancellationRequested || _outgoingQueue.Count > 0)
            {
                Tuple <IPEndPoint, ICommand, int> message;
                try {
                    message = _outgoingQueue.Take(_cancel.Token);
                } catch (Exception e) {
                    // we still send messages until we are done
                    if (_outgoingQueue.Count > 0)
                    {
                        message = _outgoingQueue.Take();
                    }
                    else
                    {
                        break;
                    }
                }
                IPEndPoint target  = message.Item1;
                ICommand   command = message.Item2;
                int        tries   = message.Item3;
                int        attempt = _maxTries - tries + 1;
                bool       retry   = false;

                Type commandType = command.GetType();
                if (command is CryptoCommand)
                {
                    CryptoCommand c = (CryptoCommand)command;
                    commandType = c.GetEncapsulatedType();
                }

                if (tries > 0)
                {
                    if (Parent.Logger != null && !(command is IsAliveCommand))
                    {
                        Parent.Logger.Log("Attempt #" + attempt + " to send " + commandType + " to " + target, Level.Info);
                    }
                    if (!(command is PublicKeyExchangeCommand || command is IsAliveCommand ||
                          command is CryptoCommand || command is DisconnectStationCommand))
                    {
                        if (Parent.Peers.ContainsKey(target))
                        {
                            command = new CryptoCommand(Parent, target, command);
                        }
                        else
                        {
                            if (Parent.Logger != null)
                            {
                                Parent.Logger.Log("Attempt to send a message to non-peer " + target, Level.Error);
                            }
                            return;
                        }
                    }

                    TcpClient client = new TcpClient();
                    client.ReceiveTimeout = _tcpTimeout;
                    WaitHandle wh = null;

                    try {
                        IAsyncResult ar = client.BeginConnect(target.Address, target.Port, null, null);
                        wh = ar.AsyncWaitHandle;

                        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(2000), false))
                        {
                            throw new SocketException();
                        }
                        client.EndConnect(ar);
                    } catch (SocketException e) {
                        if (Parent.Logger != null)
                        {
                            Parent.Logger.Log("Problem sending due to SocketException " + e + ", retrying.", Level.Error);
                        }
                        else
                        {
                            Console.WriteLine("Problem sending due to SocketException " + e + ", retrying.");
                        }
                        retry = true;
                    } finally {
                        if (wh != null)
                        {
                            wh.Close();
                        }
                    }

                    if (!retry)
                    {
                        byte[] commandBytes = Bytes.From(command);
                        byte[] length       = BitConverter.GetBytes(commandBytes.Count());
                        using (NetworkStream stream = client.GetStream()) {
                            try {
                                stream.Write(length, 0, length.Count());
                                stream.Write(commandBytes, 0, commandBytes.Count());

                                if (Parent.Logger != null)
                                {
                                    Parent.Logger.Log(commandType + " successfully sent to " + target + " on attempt #" + attempt, Level.Info);
                                }
                                else
                                {
                                    Console.WriteLine(commandType + " successfully sent to " + target + " on attempt #" + attempt);
                                }
                            } catch (Exception e) {
                                if (Parent.Logger != null)
                                {
                                    Parent.Logger.Log(commandType + " failed to " + target + " on attempt #" + attempt + ": " + e, Level.Info);
                                }
                                else
                                {
                                    Console.WriteLine(commandType + " failed to " + target + " on attempt #" + attempt + ": " + e);
                                }
                                if (!(command is DisconnectStationCommand))
                                {
                                    retry = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (Parent.Logger != null)
                    {
                        Parent.Logger.Log("Maximum number of retries reached, recording absent host " + target, Level.Error);
                    }
                    else
                    {
                        Console.WriteLine("Maximum number of retries reached, recording absent host " + target);
                    }
                    if (Parent.IsManager && Parent.Peers.ContainsKey(target))
                    {
                        Console.WriteLine("I am manager, alerting other peers of absent host.");
                        Parent.AnnounceRemovePeer(target);
                        Parent.RemovePeer(target, false);
                    }
                    else if (target.Equals(Parent.Manager))
                    {
                        Console.WriteLine("Absent host was manager, attempting to elect new manager.");
                        Parent.StartNewManagerElection();
                    }
                    else
                    {
                        Parent.RemovePeer(target, false);
                    }
                }

                if (retry)
                {
                    Send(command, target, tries - 1);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Start the client and establish a connection to the server.
        /// </summary>
        /// <returns></returns>
        public Task StartAsync()
        {
            _Client = new TcpClient();
            IAsyncResult asyncResult    = null;
            WaitHandle   waitHandle     = null;
            bool         connectSuccess = false;

            if (_Mode == Mode.Tcp)
            {
                #region TCP

                Log("Watson TCP client connecting to " + _ServerIp + ":" + _ServerPort);

                _Client.LingerState = new LingerOption(true, 0);
                asyncResult         = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
                waitHandle          = asyncResult.AsyncWaitHandle;

                try
                {
                    connectSuccess = waitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false);
                    if (!connectSuccess)
                    {
                        _Client.Close();
                        throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                    }

                    _Client.EndConnect(asyncResult);

                    _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                    _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;
                    _TcpStream  = _Client.GetStream();
                    _SslStream  = null;

                    Connected = true;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    waitHandle.Close();
                }

                #endregion TCP
            }
            else if (_Mode == Mode.Ssl)
            {
                #region SSL

                Log("Watson TCP client connecting with SSL to " + _ServerIp + ":" + _ServerPort);

                _Client.LingerState = new LingerOption(true, 0);
                asyncResult         = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
                waitHandle          = asyncResult.AsyncWaitHandle;

                try
                {
                    connectSuccess = waitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false);
                    if (!connectSuccess)
                    {
                        _Client.Close();
                        throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                    }

                    _Client.EndConnect(asyncResult);

                    _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                    _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;

                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_Client.GetStream(), false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_Client.GetStream(), false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertificateCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }

                    Connected = true;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    waitHandle.Close();
                }

                #endregion SSL
            }
            else
            {
                throw new ArgumentException("Unknown mode: " + _Mode.ToString());
            }

            if (ServerConnected != null)
            {
                Task serverConnected = Task.Run(() => ServerConnected());
            }

            return(DataReceiver());
        }
コード例 #9
0
        /// <summary>
        /// Establish a connection to the server.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                Logger?.Invoke(_Header + "already connected");
                return;
            }
            else
            {
                Logger?.Invoke(_Header + "initializing client");

                InitializeClient(_Ssl, _PfxCertFilename, _PfxPassword);

                Logger?.Invoke(_Header + "connecting to " + ServerIpPort);
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;

            IAsyncResult ar = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(_Settings.ConnectTimeoutMs), false))
                {
                    _Client.Close();
                    throw new TimeoutException("Timeout connecting to " + ServerIpPort);
                }

                _Client.EndConnect(ar);
                _NetworkStream = _Client.GetStream();

                if (_Ssl)
                {
                    if (_Settings.AcceptInvalidCertificates)
                    {
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }
                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }
                    if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                if (_Keepalive.EnableTcpKeepAlives)
                {
                    EnableKeepalives();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            _IsConnected  = true;
            _LastActivity = DateTime.Now;
            _IsTimeout    = false;
            _Events.HandleConnected(this, new ClientConnectedEventArgs(ServerIpPort));
            _DataReceiver      = Task.Run(() => DataReceiver(_Token), _Token);
            _IdleServerMonitor = Task.Run(() => IdleServerMonitor(), _Token);
        }
コード例 #10
0
ファイル: WatsonTcpClient.cs プロジェクト: sdyiheng/WatsonTcp
        /// <summary>
        /// Initialize the Watson TCP client.
        /// </summary>
        /// <param name="serverIp">The IP address or hostname of the server.</param>
        /// <param name="serverPort">The TCP port on which the server is listening.</param>
        /// <param name="serverConnected">Function to be called when the server connects.</param>
        /// <param name="serverDisconnected">Function to be called when the connection is severed.</param>
        /// <param name="messageReceived">Function to be called when a message is received.</param>
        /// <param name="debug">Enable or debug logging messages.</param>
        public WatsonTcpClient(
            string serverIp,
            int serverPort,
            Func <bool> serverConnected,
            Func <bool> serverDisconnected,
            Func <byte[], bool> messageReceived,
            bool debug)
        {
            if (String.IsNullOrEmpty(serverIp))
            {
                throw new ArgumentNullException(nameof(serverIp));
            }

            if (serverPort < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(serverPort));
            }

            _ServerIp   = serverIp;
            _ServerPort = serverPort;

            _ServerConnected    = serverConnected;
            _ServerDisconnected = serverDisconnected;
            _MessageReceived    = messageReceived ?? throw new ArgumentNullException(nameof(messageReceived));

            _Debug = debug;

            _SendLock = new SemaphoreSlim(1);

            _Client = new TcpClient();
            IAsyncResult ar = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                {
                    _Client.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                }

                _Client.EndConnect(ar);

                _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;
                _Connected  = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            if (_ServerConnected != null)
            {
                Task.Run(() => _ServerConnected());
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;
            Task.Run(async() => await DataReceiver(_Token), _Token);
        }
コード例 #11
0
        /// <summary>
        /// Connect to the server.
        /// </summary>
        public void Connect()
        {
            if (Connected)
            {
                throw new InvalidOperationException("Already connected to the server.");
            }

            _Client     = new TcpClient();
            _Statistics = new WatsonTcpStatistics();

            IAsyncResult asyncResult    = null;
            WaitHandle   waitHandle     = null;
            bool         connectSuccess = false;

            if (!_Events.IsUsingMessages && !_Events.IsUsingStreams)
            {
                throw new InvalidOperationException("One of either 'MessageReceived' or 'StreamReceived' events must first be set.");
            }

            if (_Keepalive.EnableTcpKeepAlives)
            {
                EnableKeepalives();
            }

            if (_Mode == Mode.Tcp)
            {
                #region TCP

                _Settings.Logger?.Invoke(_Header + "connecting to " + _ServerIp + ":" + _ServerPort);

                _Client.LingerState = new LingerOption(true, 0);
                asyncResult         = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
                waitHandle          = asyncResult.AsyncWaitHandle;

                try
                {
                    connectSuccess = waitHandle.WaitOne(TimeSpan.FromSeconds(_Settings.ConnectTimeoutSeconds), false);
                    if (!connectSuccess)
                    {
                        _Client.Close();
                        throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                    }

                    _Client.EndConnect(asyncResult);

                    _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                    _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;
                    _TcpStream  = _Client.GetStream();
                    _DataStream = _TcpStream;
                    _SslStream  = null;

                    Connected = true;
                }
                catch (Exception e)
                {
                    _Events.HandleExceptionEncountered(this, new ExceptionEventArgs(e));
                    throw;
                }
                finally
                {
                    waitHandle.Close();
                }

                #endregion TCP
            }
            else if (_Mode == Mode.Ssl)
            {
                #region SSL

                _Settings.Logger?.Invoke(_Header + "connecting with SSL to " + _ServerIp + ":" + _ServerPort);

                _Client.LingerState = new LingerOption(true, 0);
                asyncResult         = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
                waitHandle          = asyncResult.AsyncWaitHandle;

                try
                {
                    connectSuccess = waitHandle.WaitOne(TimeSpan.FromSeconds(_Settings.ConnectTimeoutSeconds), false);
                    if (!connectSuccess)
                    {
                        _Client.Close();
                        throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                    }

                    _Client.EndConnect(asyncResult);

                    _SourceIp   = ((IPEndPoint)_Client.Client.LocalEndPoint).Address.ToString();
                    _SourcePort = ((IPEndPoint)_Client.Client.LocalEndPoint).Port;

                    if (_Settings.AcceptInvalidCertificates)
                    {
                        _SslStream = new SslStream(_Client.GetStream(), false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        _SslStream = new SslStream(_Client.GetStream(), false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertificateCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }

                    _DataStream = _SslStream;

                    Connected = true;
                }
                catch (Exception e)
                {
                    _Events.HandleExceptionEncountered(this, new ExceptionEventArgs(e));
                    throw;
                }
                finally
                {
                    waitHandle.Close();
                }

                #endregion SSL
            }
            else
            {
                throw new ArgumentException("Unknown mode: " + _Mode.ToString());
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;

            _DataReceiver         = Task.Run(() => DataReceiver(), _Token);
            _MonitorSyncResponses = Task.Run(() => MonitorForExpiredSyncResponses(), _Token);
            _Events.HandleServerConnected(this, new ConnectionEventArgs((_ServerIp + ":" + _ServerPort)));
            _Settings.Logger?.Invoke(_Header + "connected");
        }
コード例 #12
0
        /// <summary>
        /// Initialize the Watson TCP client.
        /// </summary>
        /// <param name="serverIp">The IP address or hostname of the server.</param>
        /// <param name="serverPort">The TCP port on which the server is listening.</param>
        /// <param name="pfxCertFile">The file containing the SSL certificate.</param>
        /// <param name="pfxCertPass">The password for the SSL certificate.</param>
        /// <param name="acceptInvalidCerts">True to accept invalid or expired SSL certificates.</param>
        /// <param name="mutualAuthentication">True to mutually authenticate client and server.</param>
        /// <param name="serverConnected">Function to be called when the server connects.</param>
        /// <param name="serverDisconnected">Function to be called when the connection is severed.</param>
        /// <param name="messageReceived">Function to be called when a message is received.</param>
        /// <param name="debug">Enable or debug logging messages.</param>
        public WatsonTcpSslClient(
            string serverIp,
            int serverPort,
            string pfxCertFile,
            string pfxCertPass,
            bool acceptInvalidCerts,
            bool mutualAuthentication,
            Func <bool> serverConnected,
            Func <bool> serverDisconnected,
            Func <byte[], bool> messageReceived,
            bool debug)
        {
            if (String.IsNullOrEmpty(serverIp))
            {
                throw new ArgumentNullException(nameof(serverIp));
            }
            if (serverPort < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(serverPort));
            }
            if (messageReceived == null)
            {
                throw new ArgumentNullException(nameof(messageReceived));
            }

            if (serverConnected != null)
            {
                ServerConnected = serverConnected;
            }
            else
            {
                ServerConnected = null;
            }

            if (serverDisconnected != null)
            {
                ServerDisconnected = serverDisconnected;
            }
            else
            {
                ServerDisconnected = null;
            }

            ServerIp           = serverIp;
            ServerPort         = serverPort;
            Debug              = debug;
            AcceptInvalidCerts = acceptInvalidCerts;
            MessageReceived    = messageReceived;
            SendLock           = new SemaphoreSlim(1);

            SslCertificate = null;
            if (String.IsNullOrEmpty(pfxCertPass))
            {
                SslCertificate = new X509Certificate2(pfxCertFile);
            }
            else
            {
                SslCertificate = new X509Certificate2(pfxCertFile, pfxCertPass);
            }

            SslCertificateCollection = new X509Certificate2Collection();
            SslCertificateCollection.Add(SslCertificate);

            Tcp = new TcpClient();
            IAsyncResult ar = Tcp.BeginConnect(ServerIp, ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                {
                    Tcp.Close();
                    throw new TimeoutException("Timeout connecting to " + ServerIp + ":" + ServerPort);
                }

                Tcp.EndConnect(ar);

                SourceIp   = ((IPEndPoint)Tcp.Client.LocalEndPoint).Address.ToString();
                SourcePort = ((IPEndPoint)Tcp.Client.LocalEndPoint).Port;

                if (AcceptInvalidCerts)
                {
                    // accept invalid certs
                    Ssl = new SslStream(Tcp.GetStream(), false, new RemoteCertificateValidationCallback(AcceptCertificate));
                }
                else
                {
                    // do not accept invalid SSL certificates
                    Ssl = new SslStream(Tcp.GetStream(), false);
                }

                Ssl.AuthenticateAsClient(ServerIp, SslCertificateCollection, SslProtocols.Tls12, !AcceptInvalidCerts);

                if (!Ssl.IsEncrypted)
                {
                    throw new AuthenticationException("Stream is not encrypted");
                }
                if (!Ssl.IsAuthenticated)
                {
                    throw new AuthenticationException("Stream is not authenticated");
                }
                if (mutualAuthentication && !Ssl.IsMutuallyAuthenticated)
                {
                    throw new AuthenticationException("Mutual authentication failed");
                }

                Connected = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            if (ServerConnected != null)
            {
                Task.Run(() => ServerConnected());
            }

            TokenSource = new CancellationTokenSource();
            Token       = TokenSource.Token;
            Task.Run(async() => await DataReceiver(Token), Token);
        }
コード例 #13
0
ファイル: WeChatLink.cs プロジェクト: TonyDongGuaPi/joework
        public void BeginGetGameZoneUrl(Dictionary <string, string> userDataDict, Action <Dictionary <string, string> > action)
        {
            this.userData        = userDataDict;
            this.callbackForGame = action;
            string           text = "wzry.broker.tplay.qq.com";
            int              num  = 5692;
            List <IPAddress> list = new List <IPAddress>();

            if (text.get_Length() > 0)
            {
                try
                {
                    IPAddress iPAddress = null;
                    if (IPAddress.TryParse(text, ref iPAddress))
                    {
                        list.Add(iPAddress);
                    }
                    else
                    {
                        IPHostEntry hostEntry   = Dns.GetHostEntry(text);
                        IPAddress[] addressList = hostEntry.get_AddressList();
                        for (int i = 0; i < addressList.Length; i++)
                        {
                            IPAddress iPAddress2 = addressList[i];
                            list.Add(iPAddress2);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Log(ex.get_Message());
                    this.NotifyShowZone(false);
                }
            }
            if (list.get_Count() > 0)
            {
                int        num2       = new Random().Next(list.get_Count());
                IPEndPoint iPEndPoint = new IPEndPoint(list.get_Item(num2), num);
                Socket     socket     = new Socket(2, 1, 6);
                socket.SetSocketOption(65535, 4101, this.sendRcvTimeOut);
                socket.SetSocketOption(65535, 4102, this.sendRcvTimeOut);
                Debug.Log("Begin Connet");
                IAsyncResult asyncResult     = socket.BeginConnect(iPEndPoint, null, null);
                WaitHandle   asyncWaitHandle = asyncResult.get_AsyncWaitHandle();
                try
                {
                    if (!asyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds((double)this.connectTimeOut)))
                    {
                        Debug.Log("Connect Time Out:" + this.connectTimeOut.ToString());
                        this.CloseSocket(socket);
                    }
                    else
                    {
                        try
                        {
                            socket.EndConnect(asyncResult);
                            if (asyncResult.get_IsCompleted())
                            {
                                string actReqJson = this.GetActReqJson();
                                this.AsynCallBroker(socket, actReqJson);
                            }
                        }
                        catch (Exception ex2)
                        {
                            Debug.Log(ex2.get_Message());
                            this.CloseSocket(socket);
                        }
                    }
                }
                catch (Exception ex3)
                {
                    Debug.Log(ex3.get_Message());
                    this.CloseSocket(socket);
                }
                finally
                {
                    asyncWaitHandle.Close();
                }
            }
        }
コード例 #14
0
ファイル: WeChatLink.cs プロジェクト: TonyDongGuaPi/joework
 private void AsynCallBroker(Socket socket, string message)
 {
     if (socket == null || message == string.Empty)
     {
         return;
     }
     Debug.Log(string.Empty);
     try
     {
         int num = 9000;
         Dictionary <string, object> dictionary = new Dictionary <string, object>();
         dictionary.set_Item("seq_id", 1);
         dictionary.set_Item("cmd_id", num);
         dictionary.set_Item("type", 1);
         dictionary.set_Item("from_ip", "10.0.0.108");
         dictionary.set_Item("process_id", 1);
         dictionary.set_Item("mod_id", 10);
         dictionary.set_Item("version", this.kSDKVersion);
         dictionary.set_Item("body", message);
         dictionary.set_Item("app_id", this.userData.get_Item("sAppId"));
         string text   = Json.Serialize(dictionary);
         string text2  = MinizLib.Compress(text.get_Length(), text);
         byte[] array  = Convert.FromBase64String(text2);
         int    num2   = IPAddress.HostToNetworkOrder(array.Length);
         byte[] bytes  = BitConverter.GetBytes(num2);
         byte[] array2 = new byte[bytes.Length + array.Length];
         Array.Copy(bytes, 0, array2, 0, bytes.Length);
         Array.Copy(array, 0, array2, bytes.Length, array.Length);
         IAsyncResult asyncResult     = socket.BeginSend(array2, 0, array2.Length, 0, null, null);
         WaitHandle   asyncWaitHandle = asyncResult.get_AsyncWaitHandle();
         try
         {
             if (!asyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds((double)this.sendRcvTimeOut)))
             {
                 Debug.Log("Send Time Out:" + this.sendRcvTimeOut.ToString());
                 this.CloseSocket(socket);
             }
             else
             {
                 try
                 {
                     int num3 = socket.EndSend(asyncResult);
                     if (asyncResult.get_IsCompleted() && num3 == array2.Length)
                     {
                         Debug.Log(string.Format("客户端发送消息:{0}", text));
                         this.AsynRecive(socket);
                     }
                     else
                     {
                         this.CloseSocket(socket);
                     }
                 }
                 catch (Exception ex)
                 {
                     Debug.Log(ex.get_Message());
                     this.CloseSocket(socket);
                 }
             }
         }
         catch (Exception ex2)
         {
             Debug.Log(ex2.get_Message());
             this.CloseSocket(socket);
         }
         finally
         {
             asyncWaitHandle.Close();
         }
     }
     catch (Exception ex3)
     {
         Debug.Log(string.Format("异常信息:{0}", ex3.get_Message()));
         this.CloseSocket(socket);
     }
 }
コード例 #15
0
ファイル: Program1.cs プロジェクト: rhk1a17/Dashboard_UWP
        public static void ModbusTcpMasterReadRegisters_SMA_MPPTs()
        {
            string workingDirectory = Directory.GetCurrentDirectory();

            string[] ini_lines = new string[1];
            try
            {
                ini_lines[0] = "IP:192.168.1.170";
            }

            catch (Exception e)
            {
                Debug.WriteLine(e.Message + '\n');
                return;
            }

            List <IpInformation> IP_Information = new List <IpInformation>();
            int    ipTimeout  = DEFAULT_IP_TIMEOUT_SECONDS;
            int    ipPort     = DEFAULT_IP_PORT;
            byte   unitID     = DEFAULT_UNIT_ID;
            int    mpptCount  = DEFAULT_MPPT_COUNT;
            string historyDir = DEFAULT_HISTORY_DIRECTORY_PATH;

            foreach (string line in ini_lines)
            {
                if (line.Trim().StartsWith("#"))
                {
                    continue;
                }

                Match match;
                if ((match = regex_get_IP.Match(line)).Success)
                {
                    string ipString = match.Groups["ip"].Value;
                    if ((match = regex_get_PORT.Match(line)).Success)
                    {
                        ipPort = Convert.ToInt32(match.Groups["port"].Value);
                    }
                    if ((match = regex_get_UNIT_ID.Match(line)).Success)
                    {
                        unitID = Convert.ToByte(match.Groups["unitID"].Value);
                    }
                    if ((match = regex_get_MPPTS.Match(line)).Success)
                    {
                        mpptCount = Convert.ToInt32(match.Groups["MPPTs"].Value);
                    }
                    IP_Information.Add(new IpInformation(ipString, ipPort, unitID, mpptCount));
                }
                else if ((match = regex_get_IP_TIMEOUT.Match(line)).Success)
                {
                    ipTimeout = Convert.ToInt32(match.Groups["ipTimeout"].Value);
                }
                else if ((match = regex_get_HISTORY_DIR.Match(line)).Success)
                {
                    historyDir = match.Groups["historyDir"].Value;

                    if (historyDir.StartsWith("\"") && historyDir.EndsWith("\""))
                    {
                        historyDir = historyDir.Substring(1, historyDir.Length - 2);
                    }

                    if (historyDir.EndsWith("\\") || historyDir.EndsWith("/"))
                    {
                        historyDir = historyDir.Substring(0, historyDir.Length - 1);
                    }
                }
            }

            for (; ;)
            {
                foreach (IpInformation ipInfo in IP_Information)
                {
                    using (TcpClient client = new TcpClient())
                    {
                        try
                        {
                            //Communicate with inverter
                            Debug.WriteLine("\nConnecting to " + ipInfo.IP_Address);
                            IAsyncResult ar = client.BeginConnect(ipInfo.IP_Address, ipInfo.IP_Port, null, null);
                            WaitHandle   wh = ar.AsyncWaitHandle;
                            try
                            {
                                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(ipTimeout), false))
                                {
                                    client.Close();
                                    throw new TimeoutException("Could not connect to " + ipInfo.IP_Address);
                                }
                            }
                            finally
                            {
                                wh.Close();
                            }

                            ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                            string         line   = string.Empty;

                            //******************************************DESIRED PARAMETERS*****************************************************
                            //******************************************Refer to the datasheet*************************************************
                            //******************************************2 MPPTS****************************************************************
                            //Get local time from computer.
                            const string DATE_TIME_PATTERN = "HH:mm:ss";
                            DateTime     timeNow           = DateTime.Now;

                            try
                            {
                                if (timeNow.ToShortTimeString() == "00:00 AM")
                                {
                                    Thread.Sleep(60000);
                                }
                            }
                            catch
                            {
                                Debug.WriteLine("");
                            }

                            string dtComputer = timeNow.ToString(DATE_TIME_PATTERN);
                            line += dtComputer;


                            //Get inverter serial number.
                            const ushort SERIAL_NUMBER_ADR            = 30005;
                            const ushort SERIAL_NUMBER_REGISTER_COUNT = 2;
                            // Read SMA serial number registers (U32)
                            ushort[] serialNumberInfo = master.ReadHoldingRegisters(ipInfo.UnitID, SERIAL_NUMBER_ADR, SERIAL_NUMBER_REGISTER_COUNT);
                            // Extract fields from U32
                            UInt32 serialNumber = ((UInt32)serialNumberInfo[0] << 16) | (UInt32)serialNumberInfo[1];
                            line += "," + serialNumber;

                            //MPPT count.
                            line += "," + ipInfo.MPPT_Count;
                            if (ipInfo.MPPT_Count > 0)
                            {
                                // Get inverter DC input 1 parameters.
                                const ushort DC_1_ADR            = 30769;
                                const ushort DC_1_REGISTER_COUNT = 6;
                                // Read SMA DC 1 registers (3 x S32)
                                ushort[] DC1Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_1_ADR, DC_1_REGISTER_COUNT);
                                // Extract fields from DC 1 Current S32 (FIX3)
                                if (DC1Info[0] == 32768)
                                {
                                    DC1Info[0] = 0;
                                }
                                if (DC1Info[2] == 32768)
                                {
                                    DC1Info[2] = 0;
                                }
                                if (DC1Info[4] == 32768)
                                {
                                    DC1Info[4] = 0;
                                }

                                double DC1_Current = (double)(Int32)(((UInt32)DC1Info[0] << 16) | (UInt32)DC1Info[1]) / 1000;
                                double DC1_Voltage = (double)(Int32)(((UInt32)DC1Info[2] << 16) | (UInt32)DC1Info[3]) / 100;
                                double DC1_Power   = (double)(Int32)(((UInt32)DC1Info[4] << 16) | (UInt32)DC1Info[5]);

                                line += "," + DC1_Current + "," + DC1_Voltage + "," + DC1_Power;
                            }

                            // Get inverter DC input 2 parameters.
                            if (ipInfo.MPPT_Count > 1)
                            {
                                const ushort DC_2_ADR            = 30957;
                                const ushort DC_2_REGISTER_COUNT = 6;
                                // Read SMA DC 2 registers (3 x S32)
                                ushort[] DC2Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_2_ADR, DC_2_REGISTER_COUNT);
                                // Extract fields from DC 2 Current S32 (FIX3)
                                if (DC2Info[0] == 32768)
                                {
                                    DC2Info[0] = 0;
                                }
                                if (DC2Info[2] == 32768)
                                {
                                    DC2Info[2] = 0;
                                }
                                if (DC2Info[4] == 32768)
                                {
                                    DC2Info[4] = 0;
                                }
                                double DC2_Current = (double)(Int32)(((UInt32)DC2Info[0] << 16) | (UInt32)DC2Info[1]) / 1000;
                                double DC2_Voltage = (double)(Int32)(((UInt32)DC2Info[2] << 16) | (UInt32)DC2Info[3]) / 100;
                                double DC2_Power   = (double)(Int32)(((UInt32)DC2Info[4] << 16) | (UInt32)DC2Info[5]);

                                line += "," + DC2_Current + "," + DC2_Voltage + "," + DC2_Power + ",";
                            }

                            if (ipInfo.MPPT_Count > 2)
                            {
                                // Get inverter DC input 3 parameters.
                                const ushort DC_3_ADR            = 30963;
                                const ushort DC_3_REGISTER_COUNT = 6;
                                // Read SMA DC 3 registers (3 x S32)
                                ushort[] DC3Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_3_ADR, DC_3_REGISTER_COUNT);
                                // Extract fields from DC 3 Current S32 (FIX3)
                                if (DC3Info[0] == 32768)
                                {
                                    DC3Info[0] = 0;
                                }
                                if (DC3Info[2] == 32768)
                                {
                                    DC3Info[2] = 0;
                                }
                                if (DC3Info[4] == 32768)
                                {
                                    DC3Info[4] = 0;
                                }
                                double DC3_Current = (double)(Int32)(((UInt32)DC3Info[0] << 16) | (UInt32)DC3Info[1]) / 1000;
                                double DC3_Voltage = (double)(Int32)(((UInt32)DC3Info[2] << 16) | (UInt32)DC3Info[3]) / 100;
                                double DC3_Power   = (double)(Int32)(((UInt32)DC3Info[4] << 16) | (UInt32)DC3Info[5]);
                                line += "," + DC3_Current + "," + DC3_Voltage + "," + DC3_Power + ",";
                            }

                            if (ipInfo.MPPT_Count > 3)
                            {
                                // Get inverter DC input 4 parameters.
                                const ushort DC_4_ADR            = 30963;
                                const ushort DC_4_REGISTER_COUNT = 6;
                                // Read SMA DC 4 registers (3 x S32)
                                ushort[] DC4Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_4_ADR, DC_4_REGISTER_COUNT);
                                // Extract fields from DC 4 Current S32 (FIX3)
                                if (DC4Info[0] == 32768)
                                {
                                    DC4Info[0] = 0;
                                }
                                if (DC4Info[2] == 32768)
                                {
                                    DC4Info[2] = 0;
                                }
                                if (DC4Info[4] == 32768)
                                {
                                    DC4Info[4] = 0;
                                }
                                double DC4_Current = (double)(Int32)(((UInt32)DC4Info[0] << 16) | (UInt32)DC4Info[1]) / 1000;
                                double DC4_Voltage = (double)(Int32)(((UInt32)DC4Info[2] << 16) | (UInt32)DC4Info[3]) / 100;
                                double DC4_Power   = (double)(Int32)(((UInt32)DC4Info[4] << 16) | (UInt32)DC4Info[5]);
                                line += "," + DC4_Current + "," + DC4_Voltage + "," + DC4_Power + ",";
                            }

                            //Get Total Yield
                            //kWh
                            const ushort DC_totalpower_ADR            = 30529;
                            const ushort DC_totalpower_REGISTER_COUNT = 2;
                            ushort[]     DCtotalpowerInfo             = master.ReadHoldingRegisters(ipInfo.UnitID, DC_totalpower_ADR, DC_totalpower_REGISTER_COUNT);
                            if (DCtotalpowerInfo[0] == 32768)
                            {
                                DCtotalpowerInfo[0] = 0;
                            }
                            double totalyield = (double)(Int32)(((UInt32)DCtotalpowerInfo[0] << 16) | (UInt32)DCtotalpowerInfo[1]);
                            line += totalyield + ",";

                            //Get current total power
                            //kWh
                            const ushort DC_currentpower_ADR            = 30775;
                            const ushort DC_currentpower_REGISTER_COUNT = 2;
                            ushort[]     DCcurrentpowerInfo             = master.ReadHoldingRegisters(ipInfo.UnitID, DC_currentpower_ADR, DC_currentpower_REGISTER_COUNT);
                            if (DCcurrentpowerInfo[0] == 32768)
                            {
                                DCcurrentpowerInfo[0] = 0;
                            }
                            double currentyield = (double)(Int32)(((UInt32)DCcurrentpowerInfo[0] << 16) | (UInt32)DCcurrentpowerInfo[1]);
                            line += currentyield + ",";

                            //Get daily power
                            //kWh
                            const ushort DC_dailypower_ADR            = 30535;
                            const ushort DC_dailypower_REGISTER_COUNT = 2;
                            ushort[]     DCdailypowerInfo             = master.ReadHoldingRegisters(ipInfo.UnitID, DC_dailypower_ADR, DC_dailypower_REGISTER_COUNT);
                            if (DCdailypowerInfo[0] == 32768)
                            {
                                DCdailypowerInfo[0] = 0;
                            }
                            double dailyyield = (double)(Int32)(((UInt32)DCdailypowerInfo[0] << 16) | (UInt32)DCdailypowerInfo[1]);
                            line += dailyyield + ",";

                            //Get Inverter condition
                            const ushort DC_condition_ADR            = 30201;
                            const ushort DC_condition_REGISTER_COUNT = 2;
                            ushort[]     DCconditionInfo             = master.ReadHoldingRegisters(ipInfo.UnitID, DC_condition_ADR, DC_condition_REGISTER_COUNT);
                            if (DCconditionInfo[0] == 32768)
                            {
                                DCconditionInfo[0] = 0;
                            }
                            double condition = (double)(Int32)(((UInt32)DCconditionInfo[0] << 16) | (UInt32)DCconditionInfo[1]);
                            line += condition + ",";

                            line += "\n";
                            //File.AppendAllText(filePath, line);
                            //File.AppendAllText(filePath_1, line);
                            Debug.WriteLine(line);
                            ConnectionString(line);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                        }
                        finally
                        {
                            if (client != null)
                            {
                                ((IDisposable)client).Dispose();
                            }
                        }
                    }
                }
                Thread.Sleep(300000);       //5 minutes sleep
            }
        }
コード例 #16
0
 public virtual void Create()
 {
     if (m_socketStatus == (int)EnumNetworkStatus.Established ||
         m_socketStatus == (int)EnumNetworkStatus.Establishing)
     {
         throw new InvalidOperationException("当前网络已建立,请先销毁");
     }
     if (m_netProtocolType == EnumNetworkType.Unknown)
     {
         throw new Exception(string.Format("暂不支持的通信协议类型:{0}", m_netProtocolType));
     }
     Interlocked.Exchange(ref m_socketStatus, (int)EnumNetworkStatus.Establishing);
     SocketStatusChanged((EnumNetworkStatus)m_socketStatus);
     try
     {
         if (m_netProtocolType == EnumNetworkType.TCP)
         {
             if (m_remoteEndPoint == null)
             {
                 throw new Exception("TCP连接远端地址不能为空");
             }
             m_socket         = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             m_socket.NoDelay = true;
             //socket自带的心跳功能
             m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, NetworkGlobal.HEART_INTERVAL);
             m_socket.NoDelay = true;
         }
         else
         {
             m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
             m_socket.IOControl(-1744830452, new byte[] { 0, 0, 0, 0 }, new byte[] { 0, 0, 0, 0 });
             //组播
             if (m_netProtocolType == EnumNetworkType.Multicast)
             {
                 if (m_remoteEndPoint == null)
                 {
                     throw new Exception("组播组的地址不能为空");//如224.2.2.2:6666
                 }
                 if (m_localEndPoint == null)
                 {
                     throw new Exception("组播本地地址不能为空");//如127.0.0.1:6666,端口必须和m_remoteEndPoint一样
                 }
                 if (m_localEndPoint.Port != m_remoteEndPoint.Port)
                 {
                     throw new Exception("组播绑定端口必须保持一致");//端口必须一样
                 }
                 m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                 m_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(m_remoteEndPoint.Address));
             }
         }
         m_socket.ReceiveBufferSize = m_socketRecvBufferSize;
         m_socket.SendBufferSize    = m_socketSendBufferSize;
         //绑定
         if (m_localEndPoint == null)
         {
             //如果仍然没指定本机地址,则分配随机端口,IP为0.0.0.0
             m_socket.Bind(new IPEndPoint(IPAddress.Any, 0));
         }
         else
         {
             //组播的本地IP不能为127.0.0.1,可以为IPAddress.Any、0.0.0.0、局域网IP
             m_socket.Bind(m_localEndPoint);
         }
         m_localEndPoint = (IPEndPoint)m_socket.LocalEndPoint;
         //TCP连接超时
         if (m_netProtocolType == EnumNetworkType.TCP)
         {
             //连接
             IAsyncResult ar         = m_socket.BeginConnect(m_remoteEndPoint, null, null);
             WaitHandle   waitHandle = ar.AsyncWaitHandle;
             //处理链接超时
             if (!waitHandle.WaitOne(TimeSpan.FromSeconds(NetworkGlobal.CONNECTION_TIMEOUT), false))
             {
                 var errMsg = string.Format("TCP连接{0}超时{1}秒.", m_remoteEndPoint, NetworkGlobal.CONNECTION_TIMEOUT);
                 throw new TimeoutException(errMsg);
             }
             m_socket.EndConnect(ar);
             waitHandle.Close();
         }
         if (Interlocked.CompareExchange(ref m_socketStatus, (int)EnumNetworkStatus.Established, (int)EnumNetworkStatus.Establishing) != (int)EnumNetworkStatus.Establishing)
         {
             //如:在连接过程中,其它线程调用了断开、销毁等函数
             throw new InvalidOperationException("连接过程中,通信状态异常");
         }
     }
     catch (Exception)
     {
         DestroySocket();
         throw;
     }
     SocketStatusChanged((EnumNetworkStatus)m_socketStatus);
     StartReceive();
 }
コード例 #17
0
 public override void OnCompleted()
 {
     waitHandle.Close();
 }
コード例 #18
0
        /// <summary>
        /// If we were not provided with a tcpClient on creation we need to create one
        /// </summary>
        private void ConnectSocket()
        {
            try
            {
                if (NetworkComms.LoggingEnabled)
                {
                    NetworkComms.Logger.Trace("Connecting TCP client with " + ConnectionInfo);
                }

                bool connectSuccess = true;
#if WINDOWS_PHONE || NETFX_CORE
                //We now connect to our target
                socket = new StreamSocket();
                socket.Control.NoDelay = !EnableNagleAlgorithmForNewConnections;

                CancellationTokenSource cancelAfterTimeoutToken = new CancellationTokenSource(NetworkComms.ConnectionEstablishTimeoutMS);

                try
                {
                    if (ConnectionInfo.LocalEndPoint != null && ConnectionInfo.LocalIPEndPoint.Address != IPAddress.IPv6Any && ConnectionInfo.LocalIPEndPoint.Address != IPAddress.Any)
                    {
                        var endpointPairForConnection = new Windows.Networking.EndpointPair(new Windows.Networking.HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString(),
                                                                                            new Windows.Networking.HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString());

                        var task = socket.ConnectAsync(endpointPairForConnection).AsTask(cancelAfterTimeoutToken.Token);
                        task.Wait();
                    }
                    else
                    {
                        var task = socket.ConnectAsync(new Windows.Networking.HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask(cancelAfterTimeoutToken.Token);
                        task.Wait();
                    }
                }
                catch (Exception)
                {
                    socket.Dispose();
                    connectSuccess = false;
                }
#else
                //We now connect to our target
                tcpClient = new TcpClient(ConnectionInfo.RemoteEndPoint.AddressFamily);

                //Start the connection using the async version
                //This allows us to choose our own connection establish timeout
                IAsyncResult ar             = tcpClient.BeginConnect(ConnectionInfo.RemoteIPEndPoint.Address, ConnectionInfo.RemoteIPEndPoint.Port, null, null);
                WaitHandle   connectionWait = ar.AsyncWaitHandle;
                try
                {
                    if (!connectionWait.WaitOne(NetworkComms.ConnectionEstablishTimeoutMS, false))
                    {
                        connectSuccess = false;
                    }
                    else
                    {
                        tcpClient.EndConnect(ar);
                    }
                }
                finally
                {
                    connectionWait.Close();
                }
#endif

                if (!connectSuccess)
                {
                    throw new ConnectionSetupException("Timeout waiting for remoteEndPoint to accept TCP connection.");
                }
            }
            catch (Exception ex)
            {
                CloseConnection(true, 17);
                throw new ConnectionSetupException("Error during TCP connection establish with destination (" + ConnectionInfo + "). Destination may not be listening or connect timed out. " + ex.ToString());
            }
        }
コード例 #19
0
ファイル: TelnetClient.cs プロジェクト: tomtangrx/cs-telnet
        public bool Reconnect()
        {
            Disconnect();

            bool result = false;

            if (string.IsNullOrEmpty(host) || port < 1)
            {
                return(result);
            }

            tcp = new TcpClient();

            tcp.SendTimeout    = (int)DataTransferTimeout.TotalMilliseconds;
            tcp.ReceiveTimeout = (int)DataTransferTimeout.TotalMilliseconds;

            ReadNotEmptyTimeout = DataTransferTimeout;

            WaitHandle wh = null;

            try
            {
                IAsyncResult ar = tcp.BeginConnect(host, port, null, null);
                wh = ar.AsyncWaitHandle;

                if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout, false))
                {
                    tcp.Close();
                    throw new TimeoutException();
                }

                tcp.EndConnect(ar);
                result = true;
            }
            catch
            {
                result = false;
            }

            if (wh != null)
            {
                wh.Close();
            }

            if (result)
            {
                try
                {
                    if (!string.IsNullOrEmpty(login) && !string.IsNullOrEmpty(passw) && LoginProc != null)
                    {
                        result = LoginProc(login, passw);
                    }
                }
                catch
                {
                    result = false;
                }
            }

            if (result)
            {
                try
                {
                    if (ConnectionCheckingProc != null)
                    {
                        result = ConnectionCheckingProc();
                    }
                }
                catch
                {
                    result = false;
                }
            }

            if (!result)
            {
                Disconnect();
            }

            return(result);
        }
コード例 #20
0
ファイル: TcpClient.cs プロジェクト: pha3z/SimpleTcp
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect()
        {
            IAsyncResult ar = _TcpClient.BeginConnect(_ServerIp, _Port, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false))
                {
                    _TcpClient.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _Port);
                }

                _TcpClient.EndConnect(ar);
                _NetworkStream = _TcpClient.GetStream();

                if (_Ssl)
                {
                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                _Connected = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            if (Connected != null)
            {
                Task.Run(() => Connected());
            }

            Task.Run(() => DataReceiver(_Token), _Token);
        }
コード例 #21
0
        private void StartConnect()
        {
            zooKeeper.State = ZooKeeper.States.CONNECTING;
            TcpClient  tempClient = null;
            WaitHandle wh         = null;

            do
            {
                if (zkEndpoints.EndPointID != -1)
                {
                    try
                    {
                        Thread.Sleep(new TimeSpan(0, 0, 0, 0, random.Next(0, 50)));
                    }
#if !NET_CORE
                    catch (ThreadInterruptedException e)
                    {
                        LOG.Error("Event thread exiting due to interruption", e);
                    }
#endif
#if NET_CORE
                    catch (Exception e)
                    {
                    }
#endif
                    if (!zkEndpoints.IsNextEndPointAvailable)
                    {
                        try
                        {
                            // Try not to spin too fast!
                            Thread.Sleep(1000);
                        }
#if !NET_CORE
                        catch (ThreadInterruptedException e)
                        {
                            LOG.Error("Event thread exiting due to interruption", e);
                        }
#endif
#if NET_CORE
                        catch (Exception e)
                        {
                        }
#endif
                    }
                }

                //advance through available connections;
                zkEndpoints.GetNextAvailableEndpoint();

                Cleanup(tempClient);
                Console.WriteLine("Opening socket connection to server {0}", zkEndpoints.CurrentEndPoint.ServerAddress);
#if !NET_CORE
                LOG.InfoFormat("Opening socket connection to server {0}", zkEndpoints.CurrentEndPoint.ServerAddress);
#endif
                tempClient             = new TcpClient();
                tempClient.LingerState = new LingerOption(false, 0);
                tempClient.NoDelay     = true;

                Interlocked.Exchange(ref initialized, 0);
                IsConnectionClosedByServer = false;

                try
                {
                    IAsyncResult ar = tempClient.BeginConnect(zkEndpoints.CurrentEndPoint.ServerAddress.Address,
                                                              zkEndpoints.CurrentEndPoint.ServerAddress.Port,
                                                              null,
                                                              null);

                    wh = ar.AsyncWaitHandle;
#if !NET_CORE
                    if (!ar.AsyncWaitHandle.WaitOne(conn.ConnectionTimeout, false))
                    {
                        Cleanup(tempClient);
                        tempClient = null;
                        throw new TimeoutException();
                    }
#else
                    if (!ar.AsyncWaitHandle.WaitOne(conn.ConnectionTimeout))
                    {
                        Cleanup(tempClient);
                        tempClient = null;
                        throw new TimeoutException();
                    }
#endif

                    //tempClient.EndConnect(ar);

                    zkEndpoints.CurrentEndPoint.SetAsSuccess();

                    break;
                }
                catch (Exception ex)
                {
                    if (ex is SocketException || ex is TimeoutException)
                    {
                        Cleanup(tempClient);
                        tempClient = null;
                        zkEndpoints.CurrentEndPoint.SetAsFailure();
#if !NET_CORE
                        LOG.WarnFormat(string.Format("Failed to connect to {0}:{1}.",
                                                     zkEndpoints.CurrentEndPoint.ServerAddress.Address.ToString(),
                                                     zkEndpoints.CurrentEndPoint.ServerAddress.Port.ToString()));
#endif
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
#if !NET_CORE
                    wh.Close();
#endif
#if NET_CORE
                    wh.Dispose();
#endif
                }
            }while (zkEndpoints.IsNextEndPointAvailable);

            if (tempClient == null)
            {
                throw KeeperException.Create(KeeperException.Code.CONNECTIONLOSS);
            }

            client = tempClient;
#if !NET_CORE
            client.GetStream().BeginRead(incomingBuffer, 0, incomingBuffer.Length, ReceiveAsynch, incomingBuffer);
#endif

#if NET_CORE
            byte[] byteData    = incomingBuffer;
            var    tokenSource = new CancellationTokenSource();
            var    token       = tokenSource.Token;
            client.GetStream().ReadAsync(incomingBuffer, 0, incomingBuffer.Length, token);
            tokenSource.Cancel();
            MyReceiveAsynch(-1, byteData);
#endif

            PrimeConnection();
        }
コード例 #22
0
        private void StartConnect()
        {
            zooKeeper.State = ZooKeeper.States.CONNECTING;
            TcpClient  tempClient = null;
            WaitHandle wh         = null;

            do
            {
                if (zkEndpoints.EndPointID != -1)
                {
                    try
                    {
                        Thread.Sleep(new TimeSpan(0, 0, 0, 0, random.Next(0, 50)));
                    }
                    catch (ThreadInterruptedException e1)
                    {
                        LOG.Warn("Unexpected exception", e1);
                    }
                    if (!zkEndpoints.IsNextEndPointAvailable)
                    {
                        try
                        {
                            // Try not to spin too fast!
                            Thread.Sleep(1000);
                        }
                        catch (ThreadInterruptedException e)
                        {
                            LOG.Warn("Unexpected exception", e);
                        }
                    }
                }

                //advance through available connections;
                zkEndpoints.GetNextAvailableEndpoint();

                Cleanup(tempClient);
                LOG.InfoFormat("Opening socket connection to server {0}", zkEndpoints.CurrentEndPoint.ServerAddress);
                tempClient             = new TcpClient();
                tempClient.LingerState = new LingerOption(false, 0);
                tempClient.NoDelay     = true;

                Interlocked.Exchange(ref initialized, 0);
                IsConnectionClosedByServer = false;

                try
                {
                    IAsyncResult ar = tempClient.BeginConnect(zkEndpoints.CurrentEndPoint.ServerAddress.Address,
                                                              zkEndpoints.CurrentEndPoint.ServerAddress.Port,
                                                              null,
                                                              null);

                    wh = ar.AsyncWaitHandle;
                    if (!ar.AsyncWaitHandle.WaitOne(conn.ConnectionTimeout, false))
                    {
                        Cleanup(tempClient);
                        tempClient = null;
                        throw new TimeoutException();
                    }

                    tempClient.EndConnect(ar);

                    break;
                }
                catch (Exception ex)
                {
                    if (ex is SocketException || ex is TimeoutException)
                    {
                        Cleanup(tempClient);
                        tempClient = null;
                        zkEndpoints.CurrentEndPoint.SetAsFailure();

                        LOG.WarnFormat(string.Format("Failed to connect to {0}:{1}.",
                                                     zkEndpoints.CurrentEndPoint.ServerAddress.Address.ToString(),
                                                     zkEndpoints.CurrentEndPoint.ServerAddress.Port.ToString()));
                    }
                    else
                    {
                        throw;
                    }
                }
                finally
                {
                    wh.Close();
                }
            }while (zkEndpoints.IsNextEndPointAvailable);

            if (tempClient == null)
            {
                throw KeeperException.Create(KeeperException.Code.CONNECTIONLOSS);
            }

            Interlocked.Exchange(ref client, tempClient);
            client.GetStream().BeginRead(incomingBuffer, 0, incomingBuffer.Length, ReceiveAsynch, Tuple.Create(client, incomingBuffer));
            PrimeConnection();
        }
コード例 #23
0
ファイル: BeamerCtrl.cs プロジェクト: DFortmann/CueController
        private void ShutterMethod(bool open)
        {
            using (TcpClient client = new TcpClient())
            {
                IAsyncResult ar = client.BeginConnect(ip, 4352, null, null);
                WaitHandle   wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        LogCtrl.ThreadSafeError("Beamer " + id + ": Timed out. (" + ip + ")");
                        return;
                    }

                    byte[] bb  = new byte[9];
                    Stream stm = client.GetStream();
                    stm.Read(bb, 0, 9);
                    if (open)
                    {
                        stm.Write(openCmd, 0, openCmd.Length);
                    }
                    else
                    {
                        stm.Write(closeCmd, 0, closeCmd.Length);
                    }
                    stm.Read(bb, 0, 9);

                    if (Encoding.UTF8.GetString(bb) == "%1AVMT=OK")
                    {
                        if (open)
                        {
                            LogCtrl.ThreadSafeSuccess("Beamer " + id + ": Opened (" + ip + ")");
                        }
                        else
                        {
                            LogCtrl.ThreadSafeSuccess("Beamer " + id + ": Closed (" + ip + ")");
                        }
                    }
                    else
                    {
                        if (open)
                        {
                            LogCtrl.ThreadSafeError("Beamer " + id + ": Error opening. (" + ip + ")");
                        }
                        else
                        {
                            LogCtrl.ThreadSafeError("Beamer " + id + ": Error closing. (" + ip + ")");
                        }
                    }

                    client.EndConnect(ar);
                }
                catch (Exception e)
                {
                    LogCtrl.ThreadSafeError("Beamer " + id + ": Error connecting. (" + ip + ")");
                    LogCtrl.ThreadSafeError(e.Message);
                }
                finally
                {
                    wh.Close();
                }
            }
        }
コード例 #24
0
        private void InternalInvoke(Action invokableAction, Action foregroundAction, TimeSpan invokeTimeout, bool sendWatsonReportNoThrow, object cancelEvent)
        {
            ExTraceGlobals.ClusterTracer.TraceDebug((long)this.GetHashCode(), "InternalInvoke calling BeginInvoke");
            IAsyncResult result          = invokableAction.BeginInvoke(new AsyncCallback(this.CompletionCallback), invokableAction);
            DateTime     utcNow          = DateTime.UtcNow;
            WaitHandle   asyncWaitHandle = result.AsyncWaitHandle;
            bool         flag            = true;
            bool         flag2           = false;

            try
            {
                if (foregroundAction != null)
                {
                    foregroundAction();
                }
                flag2 = true;
                TimeSpan timeSpan = DateTime.UtcNow.Subtract(utcNow);
                TimeSpan timeout;
                if (invokeTimeout == InvokeWithTimeout.InfiniteTimeSpan)
                {
                    timeout = invokeTimeout;
                }
                else if (timeSpan < invokeTimeout)
                {
                    timeout = invokeTimeout.Subtract(timeSpan);
                }
                else
                {
                    timeout = TimeSpan.Zero;
                }
                int num = 1;
                if (cancelEvent != null)
                {
                    num = 2;
                }
                object[] array = new object[num];
                array[0] = asyncWaitHandle;
                if (cancelEvent != null)
                {
                    array[1] = cancelEvent;
                }
                int  num2  = ManualOneShotEvent.WaitAny(array, timeout);
                bool flag3 = false;
                bool flag4 = false;
                if (num2 == 258)
                {
                    flag3 = true;
                }
                else if (num2 == 1)
                {
                    flag4 = true;
                }
                if (flag3 || flag4)
                {
                    if (flag3 && sendWatsonReportNoThrow)
                    {
                        if (this.m_asyncRefCount == 1)
                        {
                            flag3 = false;
                        }
                    }
                    else if (Interlocked.Decrement(ref this.m_asyncRefCount) == 0)
                    {
                        flag3 = false;
                        flag4 = false;
                    }
                }
                if (flag3)
                {
                    TimeoutException ex = new TimeoutException(Strings.OperationTimedOut(invokeTimeout.ToString()));
                    if (!sendWatsonReportNoThrow)
                    {
                        flag = false;
                        throw ex;
                    }
                    this.SendWatsonReport <TimeoutException>(ex);
                    invokableAction.EndInvoke(result);
                }
                else
                {
                    if (flag4)
                    {
                        OperationAbortedException ex2 = new OperationAbortedException();
                        flag = false;
                        throw ex2;
                    }
                    invokableAction.EndInvoke(result);
                }
            }
            finally
            {
                if (!flag2)
                {
                    if (Interlocked.Decrement(ref this.m_asyncRefCount) > 0)
                    {
                        flag = false;
                    }
                    else
                    {
                        Exception ex3 = this.RunOperation(delegate
                        {
                            invokableAction.EndInvoke(result);
                        });
                        if (ex3 != null)
                        {
                            ExTraceGlobals.ClusterTracer.TraceError <Exception>((long)this.GetHashCode(), "EndInvoke() has thrown an exception after the foreground thread threw an exception. Exception: {0}", ex3);
                        }
                    }
                }
                if (flag && asyncWaitHandle != null)
                {
                    asyncWaitHandle.Close();
                }
            }
        }
コード例 #25
0
        public string ExecuteCommand(MinerCommand command)
        {
            string response = string.Empty;

            byte[] byteBuffer = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(command));

            try
            {
                using (var client = new TcpClient())
                {
                    IAsyncResult ar = client.BeginConnect("localhost", PORT, null, null);

                    WaitHandle wh = ar.AsyncWaitHandle;
                    try
                    {
                        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                        {
                            client.Close();
                            throw new TimeoutException();
                        }

                        client.EndConnect(ar);
                    }
                    finally
                    {
                        wh.Close();
                    }

                    var stream = client.GetStream();
                    stream.Write(byteBuffer, 0, byteBuffer.Length);

                    var responseBytes = ReadFully(stream);
                    if (responseBytes != null && responseBytes.Length > 0)
                    {
                        response = Encoding.ASCII.GetString(responseBytes, 0, responseBytes.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                this.knownConnected = false;

                if (!(ex is SocketException))
                {
                    this.Message(this, new MessageEventArgs()
                    {
                        Message = "Unexpected error in ExecuteCommand: " + ex.ToString()
                    });
                }

                return(response);
            }

            if (command.Command != "quit")
            {
                this.consecutiveLaunches = 0; // reset consecutive launches

                if (!this.knownConnected)
                {
                    this.Connected(this, EventArgs.Empty);
                }

                this.knownConnected = true;
            }

            return(response);
        }
コード例 #26
0
 public static void Dispose(this WaitHandle semaphore)
 {
     semaphore.Close();
 }
コード例 #27
0
// </Snippet4>

    public static void Main()
    {
        int result;
        int param;

// <Snippet6>
        // Creates an instance of a context-bound type SampleSynchronized.
        SampleSynchronized sampSyncObj = new SampleSynchronized();

        // Checks whether the object is a proxy, since it is context-bound.
        if (RemotingServices.IsTransparentProxy(sampSyncObj))
        {
            Console.WriteLine("sampSyncObj is a proxy.");
        }
        else
        {
            Console.WriteLine("sampSyncObj is NOT a proxy.");
        }
// </Snippet6>
// <Snippet7>

        param = 10;

        Console.WriteLine("");
        Console.WriteLine("Making a synchronous call on the context-bound object:");

        result = sampSyncObj.Square(param);
        Console.Write("The result of calling sampSyncObj.Square with ");
        Console.WriteLine("{0} is {1}.", param, result);
        Console.WriteLine("");

// </Snippet7>
// <Snippet8>
        SampSyncSqrDelegate sampleDelegate = new SampSyncSqrDelegate(sampSyncObj.Square);

        param = 8;

        Console.WriteLine("Making a single asynchronous call on the context-bound object:");

        IAsyncResult ar1 = sampleDelegate.BeginInvoke(param,
                                                      new AsyncCallback(AsyncResultSample.MyCallback),
                                                      param);

        Console.WriteLine("Waiting for the asynchronous call to complete...");
        WaitHandle wh = ar1.AsyncWaitHandle;

        wh.WaitOne();

        wh.Close();

        Console.WriteLine("");
        Console.WriteLine("Waiting for the AsyncCallback to complete...");
        // Note that normally, a callback and a wait handle would not
        // both be used on the same asynchronous call. Callbacks are
        // useful in cases where the original thread does not need to
        // be synchronized with the result of the call, and in that
        // scenario they provide a place to call EndInvoke. Sleep is
        // used here because the callback is on a ThreadPool thread.
        // ThreadPool threads are background threads, and will not keep
        // a process running when the main thread ends.
        Thread.Sleep(1000);
// </Snippet8>
    }
コード例 #28
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect(int timeoutSeconds)
        {
            if (timeoutSeconds < 1)
            {
                throw new ArgumentException("TimeoutSeconds must be greater than zero seconds.");
            }

            IAsyncResult ar = _TcpClient.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeoutSeconds), false))
                {
                    _TcpClient.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                }

                _TcpClient.EndConnect(ar);
                _NetworkStream = _TcpClient.GetStream();

                if (_Ssl)
                {
                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            Stats = new Statistics();
            Logger?.Invoke("Starting connection monitor for: " + _ServerIp + ":" + _ServerPort);
            Task unawaited = Task.Run(() => ClientConnectionMonitor());

            ClientConnected?.Invoke(this, EventArgs.Empty);

            _IsConnected = true;
        }
コード例 #29
0
        /// <summary>
        /// The is listening.
        /// </summary>
        /// <param name="address">
        /// The address.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        [Pure] public bool IsListening(IPEndPoint address)
        {
            bool result = true;

            if (_responseTimes.ContainsKey(address) &&
                DateTime.Now.Subtract(_responseTimes[address]).TotalSeconds < 30)
            {
                // we've heard from this station within the last 30 seconds
            }
            else
            {
                // we haven't heard from this station in 30 seconds, or ever, let's ping it
                TcpClient  client = new TcpClient();
                WaitHandle wh     = null;

                try {
                    IAsyncResult ar = client.BeginConnect(address.Address, address.Port, null, null);
                    wh = ar.AsyncWaitHandle;

                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(2000), false))
                    {
                        throw new SocketException();
                    }
                    client.EndConnect(ar);
                } catch (SocketException e) {
                    if (Parent.Logger != null)
                    {
                        Parent.Logger.Log("Could not connect to " + address + ", assuming down. " + e, Level.Error);
                    }
                    else
                    {
                        Console.WriteLine("Could not connect to " + address + ", assuming down. " + e);
                    }
                    result = false;
                } finally {
                    if (wh != null)
                    {
                        wh.Close();
                    }
                }

                if (result)
                {
                    byte[] bytes       = Bytes.From(new IsAliveCommand(Parent.Address));
                    byte[] lengthBytes = BitConverter.GetBytes(bytes.Count());
                    using (NetworkStream stream = client.GetStream()) {
                        try {
                            stream.Write(lengthBytes, 0, lengthBytes.Count());
                            stream.Write(bytes, 0, bytes.Count());
                        } catch (Exception e) {
                            if (Parent.Logger != null)
                            {
                                Parent.Logger.Log("Could not send IsAlive command to " + address + ", assuming down." + e, Level.Error);
                            }
                            else
                            {
                                Console.WriteLine("Could not send IsAlive command to " + address + ", assuming down." + e);
                            }
                            result = false;
                        }
                    }
                }
            }
            return(result);
        }