Beispiel #1
0
        public void PingHandler(INetworkStream stream)
        {
            var buffer = new byte[PingSize];

            using (var timer = new Timer(_ =>
            {
                stream.Dispose();
            }, null, TimeSpan.Zero, PingTimeout))
            {
                while (true)
                {
                    if (stream?.ReadFull(buffer) != buffer.Length)
                    {
                        break;
                    }

                    if (stream?.Write(buffer, 0, buffer.Length) != buffer.Length)
                    {
                        break;
                    }

                    timer.Change(TimeSpan.Zero, PingTimeout);
                }
            }
        }
Beispiel #2
0
        private TimeSpan Ping(INetworkStream stream)
        {
            var buffer = new byte[PingSize];

            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetNonZeroBytes(buffer);
            }

            var sw = new Stopwatch();

            sw.Start();

            if (stream.Write(buffer, 0, buffer.Length) != buffer.Length)
            {
                return(TimeSpan.Zero);
            }

            var rbuf = new byte[PingSize];

            if (stream.ReadFull(rbuf) != rbuf.Length)
            {
                return(TimeSpan.Zero);
            }

            if (!rbuf.SequenceEqual(buffer))
            {
                return(TimeSpan.Zero);
            }

            sw.Stop();
            return(sw.Elapsed);
        }