Ejemplo n.º 1
0
        public void Start()
        {
            _tcpListener.Start();
            _tcpListener.AcceptSocketAsync().ContinueWith(OnTcpSocketAccept);

            _streamCopier.Start();
        }
Ejemplo n.º 2
0
        public static async Task RunAsync(IMvcApplication application, int port)
        {
            ServerRoutingTable = new ServerRoutingTable();
            IServiceCollection serviceCollection = new ServiceCollection();

            application.ConfigureServices(serviceCollection);
            application.Configure(ServerRoutingTable);

            ServerRoutingTable
            .LoadControllers(application.GetType().Assembly, serviceCollection)
            .LoadStaticFiles();

            Console.WriteLine(string.Join(Environment.NewLine, ServerRoutingTable.GetAllRouteNames()));

            TcpListener listener = new TcpListener(IPAddress.Parse(LocalhostIpAddress), port);

            listener.Start();
            IsRunning = true;

            Console.WriteLine($"Server started at http://{LocalhostIpAddress}:{port}");

            while (IsRunning)
            {
                Console.WriteLine("Waiting for client...");

                var client = await listener.AcceptSocketAsync();

                ListenAsync(client);
            }
        }
Ejemplo n.º 3
0
        private Task <Socket> Accept()
        {
            if (tcpListener == null)
            {
                ///同时支持IPv4和IPv6
                tcpListener = TcpListener.Create(ConnectIPEndPoint.Port);

                tcpListener.AllowNatTraversal(true);
            }

            tcpListener.Start();
            Socket remoteSocket = null;

            try
            {
                ///此处有远程连接拒绝异常
                return(tcpListener.AcceptSocketAsync());
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e);
                ///出现异常重新开始监听
                tcpListener = null;
                return(Accept());
            }
        }
        private async Task ListenLoop()
        {
            while (true)
            {
                Socket socket;
                try
                {
                    socket = await _tcpListener.AcceptSocketAsync().ConfigureAwait(false);
                }
                catch
                {
                    socket = null;
                }

                if (socket == null)
                {
                    break;
                }

                var client = new MLLPClient(socket);

                if (!_clients.TryAdd(client.Id, client))
                {
                    //duplicated id
                    client.Disconnect();
                    continue;
                }
            }
        }
Ejemplo n.º 5
0
        public async Task Run(Settings settings)
        {
            Settings = settings;

            var local    = settings.Local;
            var listener = new TcpListener(local.Listen, local.Port);

            listener.Start();

            var pairIdSeed = 0;

            while (true)
            {
                var client = await listener.AcceptSocketAsync();

                var pairId = Interlocked.Increment(ref pairIdSeed);
                _ = Task.Run(async() =>
                {
                    var command = Negotiate(client);
                    if (command != null)
                    {
                        var cmd = command.Value;
                        await SendMessageAsync($"+E {pairId} {cmd.act} {cmd.addr}");
                        EndPointStation.AddEndPoint(pairId, client);
                    }
                });
            }
        }
        internal override async ValueTask <QuicConnectionProvider> AcceptConnectionAsync(CancellationToken cancellationToken = default)
        {
            CheckDisposed();

            Socket socket = await _tcpListener.AcceptSocketAsync().ConfigureAwait(false);

            socket.NoDelay = true;

            // Read first 4 bytes to get client listen port
            byte[] buffer    = new byte[4];
            int    bytesRead = 0;

            do
            {
                bytesRead += await socket.ReceiveAsync(buffer.AsMemory().Slice(bytesRead), SocketFlags.None).ConfigureAwait(false);
            } while (bytesRead != buffer.Length);

            int        peerListenPort     = BinaryPrimitives.ReadInt32LittleEndian(buffer);
            IPEndPoint peerListenEndPoint = new IPEndPoint(((IPEndPoint)socket.RemoteEndPoint !).Address, peerListenPort);

            // Listen on a new local endpoint for inbound streams
            TcpListener inboundListener = new TcpListener(_listenEndPoint.Address, 0);

            inboundListener.Start();
            int inboundListenPort = ((IPEndPoint)inboundListener.LocalEndpoint).Port;

            // Write inbound listen port to socket so client can read it
            BinaryPrimitives.WriteInt32LittleEndian(buffer, inboundListenPort);
            await socket.SendAsync(buffer, SocketFlags.None).ConfigureAwait(false);

            return(new MockConnection(socket, peerListenEndPoint, inboundListener));
        }
Ejemplo n.º 7
0
        public void Start()
        {
            _isRunning = true;

            _server = new TcpListener(IPAddress.Any, Port);

            Task.Run(async() =>
            {
                try
                {
                    _server.Start();
                    _logger.Info("Server: {0} started listening port: {1}", _name, Port);

                    while (_isRunning)
                    {
                        var client = await _server.AcceptSocketAsync();
                        OnClientConnected(client);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex);
                }
                finally
                {
                    if (_isRunning == true)
                    {
                        _isRunning = false;
                        _server.Stop();
                    }
                }
            });
        }
Ejemplo n.º 8
0
 public void Start()
 {
     informationMessage = "Beginne";
     IP4s         = GetLocalIpAdresse();
     IP4          = IPAddress.Parse(IP4s);
     IPE          = new IPEndPoint(IP4, port);
     listener     = new TcpListener(IPE);
     appserver[0] = Task.Run(async() =>
     {
         informationMessage = "Verbindungssuche.";
         try
         {
             listener.Start();
             connectionSocket   = await listener.AcceptSocketAsync();
             informationMessage = "Connected";
             networkStream      = new NetworkStream(connectionSocket);
         }
         catch (SocketException)
         {
             informationMessage = "WTF";
             listener.Stop();
             Start();
         }
     }
                             ).ContinueWith((appservice) => Receive());
 }
Ejemplo n.º 9
0
        public async Task Accept_StartAfterStop_AcceptsSuccessfully()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);

            listener.Start();
            await VerifyAccept(listener);

            listener.Stop();

            Assert.NotNull(listener.Server);

            listener.Start();
            Assert.NotNull(listener.Server);
            await VerifyAccept(listener);

            listener.Stop();

            async Task VerifyAccept(TcpListener listener)
            {
                using var client = new TcpClient();
                Task connectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);

                using Socket s = await listener.AcceptSocketAsync();

                Assert.False(listener.Pending());
                await connectTask;
            }
        }
Ejemplo n.º 10
0
        private async Task DoListenForClients(object state, CancellationToken token)
        {
            TcpListener _server = (state as TcpListener);

            while (!cancelListenToken.IsCancellationRequested)
            {
                logger.Info("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                Socket socket = await _server.AcceptSocketAsync().ConfigureAwait(false);

                // Get ID
                string id = GetIDFromSocket(socket);
                // Create Framewrapper
                var framewrapper = createFrameWrapperFunc();
                // Create Communicator
                CommunicatorBase <U> communicator = new IPSocketCommunicator <U>(socket, framewrapper);

                // Add to dict
                lock (lockerClientList)
                    ClientList.Add(id, communicator);

                // Subscribe to events
                communicator.ConnectionStateEvent += OnCommunicatorConnection;
                communicator.DataReadySyncEvent   += OnCommunicatorSyncData;
                communicator.DataReadyAsyncEvent  += OnCommunicatorAsyncData;
                framewrapper.FrameAvailableEvent  += OnFrameReady;

                communicator.Init(null, false, id, 0);
                communicator.Start();
            }
        }
Ejemplo n.º 11
0
 private static IEnumerable <IObservable <Socket> > Listen(this TcpListener listener)
 {
     while (true)
     {
         yield return(listener.AcceptSocketAsync().ToObservable());
     }
 }
Ejemplo n.º 12
0
        async void AcceptLoop()
        {
            try
            {
                while (true)
                {
                    var socket = await listener.AcceptSocketAsync();

                    lock (clients)
                    {
                        logger.Info($"Accepted client {socket.RemoteEndPoint}");
                        if (acceptSingleClient && client?.Proto.IsConnected == true)
                        {
                            logger.Info($"Closing previous connection");
                            clients.Clear();
                            client.Proto.Dispose();
                            logger.Info($"Previous connection closed");
                        }

                        client = new Simulator {
                            Logic = new SimulatorLogic()
                        };
                        client.Proto = new SimulatorProtocol(client.Logic.HandleCommand);
                        clients.Add(client);
                        client.Proto.Accept(socket);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Debug("SimulatorListener: " + ex);
            }
        }
Ejemplo n.º 13
0
        internal override async ValueTask <QuicStreamProvider> AcceptStreamAsync(CancellationToken cancellationToken = default)
        {
            CheckDisposed();

            Socket socket = await _inboundListener.AcceptSocketAsync().ConfigureAwait(false);

            // Read first bytes to get stream ID
            byte[] buffer    = new byte[8];
            int    bytesRead = 0;

            do
            {
                bytesRead += await socket.ReceiveAsync(buffer.AsMemory().Slice(bytesRead), SocketFlags.None).ConfigureAwait(false);
            } while (bytesRead != buffer.Length);

            long streamId = BinaryPrimitives.ReadInt64LittleEndian(buffer);

            bool clientInitiated = ((streamId & 0b01) == 0);

            if (clientInitiated == _isClient)
            {
                throw new Exception($"Wrong initiator on accepted stream??? streamId={streamId}, _isClient={_isClient}");
            }

            bool bidirectional = ((streamId & 0b10) == 0);

            return(new MockStream(socket, streamId, bidirectional: bidirectional));
        }
Ejemplo n.º 14
0
        public async void StartHost()
        {
            if (Main == null)
            {
                throw new InvalidOperationException(" 'Main' was null!");
            }

            server.Start();

            while (true)
            {
                var socket = await server.AcceptSocketAsync();

                var session = new TelnetSession(this, socket);
                _sessions.Add(session.ConnectionId, session);

                var e = new SessionEventArgs(session);  //todo: this client event can block the whole server
                SessionConnected?.Invoke(this, e);

                if (!e.RefuseConnection)
                {
                    session.Run();
                }
                else
                {
                    session.Kick();
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Listen tcp connections on any ip address.
        /// </summary>
        /// <returns>Task.</returns>
        public async Task Listen()
        {
            var listener = new TcpListener(IPAddress.Any, this.port);

            listener.Start();
            Console.WriteLine($"Listening on {this.port} port");

            while (true)
            {
                var socket = await listener.AcceptSocketAsync();

                Task.Run(async() =>
                {
                    try
                    {
                        await using var stream = new NetworkStream(socket);
                        await RequestHandler.Handle(stream);
                    }
                    finally
                    {
                        socket.Close();
                    }
                });
            }
        }
Ejemplo n.º 16
0
        static async Task AcceptWorkAsync()
        {
            try
            {
                while (true)
                {
                    var socket = await _listener6022.AcceptSocketAsync();

                    _ = Task.Run(async delegate
                    {
                        LogMessage("Warning:accept server " + socket.LocalEndPoint + "," + socket.RemoteEndPoint);
                        try
                        {
                            socket.InitTcp();
                            await ProcesSocketAsync(socket);
                        }
                        catch (Exception x)
                        {
                            OnError(x);
                        }
                        finally
                        {
                            LogMessage("Warning:close server " + socket.LocalEndPoint + "," + socket.RemoteEndPoint);
                            socket.CloseSocket();
                        }
                    });
                }
            }
            catch (Exception x)
            {
                OnError(x);
            }
        }
Ejemplo n.º 17
0
        public async Task <AsyncSocketSession> GetConnectedSocket(IProcessor processor)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay     = true,
                LingerState = new LingerOption(true, 2)
            };

            var serverSocketAccept = listener.AcceptSocketAsync();

            socket.Connect(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port));
            await serverSocketAccept;

            var serverSocket = serverSocketAccept.Result;

            var session = new AsyncSocketSession(Guid.NewGuid().ToString(),
                                                 socket,
                                                 processor,
                                                 SocketAwaitablePool,
                                                 BlockingBufferManager);

            serverSocketsBySession.Add(session, serverSocket);

            return(session);
        }
Ejemplo n.º 18
0
        private async Task ListenLoop()
        {
            bool running = !_exitListening;

            while (running)
            {
                lock (_lock) {
                    if (_exitListening)
                    {
                        running = false;
                    }
                }

                if (_listener.Pending())
                {
                    var socket = await _listener.AcceptSocketAsync();

                    ProcessClient(socket);
                }


                Thread.Sleep(50);
            }


            Console.WriteLine("> Stopped listening.");

            _listener.Stop();
        }
Ejemplo n.º 19
0
 public void CheckAndAccept(object nothing)
 {
     while (listener != null && listener.Pending())
     {
         TcpRosAcceptConnection(new TcpTransport(listener.AcceptSocketAsync().Result, PollManager.Instance.poll_set));
     }
 }
Ejemplo n.º 20
0
        private async void ProcessPing()
        {
            Console.Write("Waiting for a connection... ");
            while (true)
            {
                Socket client = await pingListener.AcceptSocketAsync();

                Console.WriteLine("Client connected from {0}", client.RemoteEndPoint.ToString());

                // get a thread to handle the ping from the new client connection
                var childSocketThread = new Thread(() =>
                {
                    Console.WriteLine("In ping requests processing thread...");
                    byte[] data = new byte[100];
                    while (true)
                    {
                        try
                        {
                            int size = client.Receive(data);
                            OnPingReceived(client);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Remote peer disconnected.");
                            break;
                        }
                    }
                    Console.WriteLine("Exiting ping requests processing thread...");
                });
                childSocketThread.Start();
            }
        }
Ejemplo n.º 21
0
        public async void AcceptPeersAsync()
        {
            Console.WriteLine("[Server] Waiting client connect...");
            while (!cancellationTokenSource.IsCancellationRequested)
            {
                Socket socket;
                try
                {
                    socket = await listener.AcceptSocketAsync();

                    if (socket != null)
                    {
                        connections++;
                    }
                    Console.WriteLine("[Server] New Client Connection:{0} connected.", connections);

                    byte[] myBytes = Encoding.ASCII.GetBytes("[Server]Success to connect...");
                    socket.Send(myBytes);

                    TCPRemote remote = new TCPRemote(socket);
                    Thread    thread = new Thread(remote.ReceiveMessage);
                    thread.Start();
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (SocketException)
                {
                    continue;
                }
            }
        }
Ejemplo n.º 22
0
        private static async Task ListenConnect(IPAddress address)
        {
            TcpListener listener = new TcpListener(address, PORT_NUMBER);

            listener.Start();
            Console.WriteLine("Server started on " + listener.LocalEndpoint);
            Console.WriteLine("Waiting for a connection...\n");

            try
            {
                while (true)
                {
                    Task <Socket> socket = listener.AcceptSocketAsync();

                    socket.Wait();

                    var  Reader  = new StreamReader(new NetworkStream(socket.Result));
                    User TmpUser = new User(await Reader.ReadLineAsync(), socket.Result);

                    ListUser.Add(TmpUser);

                    ReceiveMessage(TmpUser);
                    Console.WriteLine(String.Format("Connection received from {0}: {1}", socket.Result.RemoteEndPoint, TmpUser.GSName));
                }
            }
            catch { listener.Stop(); }
        }
Ejemplo n.º 23
0
        private async Task AcceptPeers()
        {
            while (true)
            {
                Socket socket;

                try
                {
                    socket = await _listener.AcceptSocketAsync();

                    _logger.LogInformation($"\"{(socket.RemoteEndPoint as IPEndPoint)?.Address}\" is connected");
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (SocketException)
                {
                    continue;
                }

                var peer = _peerFactory.CreateFrom(socket);

                OnPeerConnected?.Invoke(this, peer);
            }
        }
Ejemplo n.º 24
0
        public async void connectTcp()
        {
            tcpconnect = false;
            Console.WriteLine("CONNECTING TCP");
            while (!tcpconnect)
            {
                try
                {
                    /* Initializes the Listener */
                    myList = new TcpListener(ip, 8001);

                    /* Start Listeneting at the specified port */
                    myList.Start();
                    Console.WriteLine("The server is running at port 8001...");
                    Console.WriteLine("The local End point is  :" + myList.LocalEndpoint);
                    Console.WriteLine("...Waiting for a connection...");
                    s = await myList.AcceptSocketAsync();

                    Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
                    tcpconnect = true;
                }
                catch (SocketException connectexcept)
                {
                    Console.WriteLine("ERROR" + connectexcept.ToString());
                }
            }
            //while(true) readTcp();
        }
Ejemplo n.º 25
0
        private async Task <string[]> ForwardRequestToIoTServer()
        {
            /* Initializes the Listener */
            TcpListener tcpLis = new TcpListener(IPAddress.Any, 8001);

            /* Start Listeneting at the specified port */
            tcpLis.Start();
            Socket s = await tcpLis.AcceptSocketAsync();

            byte[] message = new byte[100];
            int    k       = s.Receive(message);

            ASCIIEncoding asen = new ASCIIEncoding();
            var           str  = asen.GetString(message, 0, k);

            string clientIP = "192.168.56.101"; //TODO

            byte[] response = asen.GetBytes(clientIP);
            s.Send(response);

            k = s.Receive(message);
            var port = asen.GetString(message, 0, k);

            /* clean up */
            s.Shutdown(SocketShutdown.Both);
            tcpLis.Stop();

            return(new string[] { port });
        }
Ejemplo n.º 26
0
        private Task <Socket> AcceptControlClient(List <Task> controlTasks)
        {
            var acceptControlClientTask = controlListener.AcceptSocketAsync();

            controlTasks.Add(acceptControlClientTask);
            return(acceptControlClientTask);
        }
Ejemplo n.º 27
0
        private async Task AcceptPeers()
        {
#if !NET47
            //There is a bug in .NET Core 2.0 that blocks async method which returns void.
            await Task.Yield();
#endif
            while (!cancellationTokenSource.IsCancellationRequested)
            {
                Socket socket;
                try
                {
                    socket = await listener.AcceptSocketAsync();
                }
                catch (ObjectDisposedException)
                {
                    break;
                }
                catch (SocketException)
                {
                    continue;
                }
                TcpRemoteNode remoteNode = new TcpRemoteNode(this, socket);
                OnConnected(remoteNode);
            }
        }
Ejemplo n.º 28
0
Archivo: TCP.cs Proyecto: Xicy/Comidat
        /// <inheritdoc />
        /// <param name="ipe">IP and Port for server to start</param>
        /// <returns></returns>
        public async Task StartAsync(IPEndPoint ipe)
        {
            // create server and put ip and port
            _server = new TcpListener(ipe);
            // init id from 0
            _id = 0;
            // start server
            _server.Start();
            // register stop method for cancellation token
            _cancellationToken.Register(_server.Stop);
            // while loop until server stopped
            while (!_cancellationToken.IsCancellationRequested)
            {
                //safe for exceptions
                try
                {
                    // accept client connection
                    var client = await _server.AcceptSocketAsync().ConfigureAwait(false);

                    // create state object for receive data from tcp connection
                    var so = new StateObject(_id++.ToString(), client);
                    // if connected not null Invoke connected event args
                    Connected?.Invoke(this, new ConnectedEventArgs(so.Id));
                    // and start receive message
                    client.BeginReceive(so.Buffer, 0, StateObject.BufferSize, 0, Receive, so);
                }
                //if objecet is disposed and server stopeed give info
                catch (ObjectDisposedException) when(_cancellationToken.IsCancellationRequested)
                {
                    Logger.Info(Localization.Get("Comidat.Controller.Server.TCP.StartAsync.ObjectDisposedException"));
                }
            }
Ejemplo n.º 29
0
        /// <summary>
        /// Start accepting connections on <see cref="Socket"/>
        /// </summary>
        private async Task acceptAsync()
        {
            // indefinitely process new connections, until exception is thrown on AcceptSocketAsync() when the listener is stopped
            while (true)
            {
                Socket socket;

                try {
                    // wait for new connection
                    socket = await _listener.AcceptSocketAsync()
                             .ConfigureAwait(false); // to avoid deadlock, continue the execution on any free thread at the time
                } catch (Exception ex) {
                    // report error only when the exception is not intentional
                    if (!_terminationSwitch)
                    {
                        // invoke the client handler to process the error in the implementation
                        ServerHandler?.OnAcceptError(ex);
                    }

                    // exception on AcceptSocketAsync means there is an error with the listener itself, so must terminate
                    break;
                }

                // invoke the connection handler to process the socket connection in implementation
                ServerHandler?.OnSocketAccepted(socket);
            }
        }
Ejemplo n.º 30
0
        private async Task CaptureModulesAsync(TcpListener listener)
        {
            try
            {
                HNode moduleNode = new HNode(await listener.AcceptSocketAsync());

                moduleNode.InFormat  = HFormat.EvaWire;
                moduleNode.OutFormat = HFormat.EvaWire;
                HPacket infoPacket = await moduleNode.ReceivePacketAsync();

                var module = new ModuleInfo(moduleNode);
                module.PropertyChanged += Module_PropertyChanged;

                module.Version     = Version.Parse(infoPacket.ReadUTF8());
                module.Name        = infoPacket.ReadUTF8();
                module.Description = infoPacket.ReadUTF8();

                module.Authors.Capacity = infoPacket.ReadInt32();
                for (int i = 0; i < module.Authors.Capacity; i++)
                {
                    module.Authors.Add(new AuthorAttribute(infoPacket.ReadUTF8()));
                }
                Modules.Add(module);

                module.Initialize();
                Task handleModuleDataTask = HandleModuleDataAsync(module);
            }
            finally { Task captureModulesAsync = CaptureModulesAsync(listener); }
        }
Ejemplo n.º 31
0
        public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
        {
            const int BytesToSend = 123456;
            const int ListenBacklog = 1;
            const int TestTimeout = 30000;

            var listener = new TcpListener(listenAt, 0);
            listener.Start(ListenBacklog);
            try
            {
                int bytesReceived = 0;
                var receivedChecksum = new Fletcher32();
                Task serverTask = Task.Run(async () =>
                {
                    using (Socket remote = await listener.AcceptSocketAsync())
                    {
                        var recvBuffer = new byte[256];
                        while (true)
                        {
                            if (pollBeforeOperation)
                            {
                                Assert.True(remote.Poll(-1, SelectMode.SelectRead), "Read poll before completion should have succeeded");
                            }
                            int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
                            if (received == 0)
                            {
                                Assert.True(remote.Poll(0, SelectMode.SelectRead), "Read poll after completion should have succeeded");
                                break;
                            }

                            bytesReceived += received;
                            receivedChecksum.Add(recvBuffer, 0, received);
                        }
                    }
                });

                int bytesSent = 0;
                var sentChecksum = new Fletcher32();
                Task clientTask = Task.Run(async () =>
                {
                    var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;

                    using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                    {
                        await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);

                        if (pollBeforeOperation)
                        {
                            Assert.False(client.Poll(TestTimeout, SelectMode.SelectRead), "Expected writer's read poll to fail after timeout");
                        }

                        var random = new Random();
                        var sendBuffer = new byte[512];
                        for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
                        {
                            random.NextBytes(sendBuffer);

                            if (pollBeforeOperation)
                            {
                                Assert.True(client.Poll(-1, SelectMode.SelectWrite), "Write poll should have succeeded");
                            }
                            sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None);

                            bytesSent += sent;
                            sentChecksum.Add(sendBuffer, 0, sent);
                        }
                    }
                });

                Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out");

                Assert.Equal(bytesSent, bytesReceived);
                Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
            }
            finally
            {
                listener.Stop();
            }
        }