Beispiel #1
0
        public async Task Connection_Dispose_ClosesSocket(bool disposeAsync, bool usePipe)
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Connection connection = await factory.ConnectAsync(server.EndPoint);

            Stream stream = usePipe ? null : connection.Stream;

            if (usePipe)
            {
                _ = connection.Pipe;
            }
            connection.ConnectionProperties.TryGet(out Socket socket);

            if (disposeAsync)
            {
                await connection.DisposeAsync();
            }
            else
            {
                connection.Dispose();
            }

            Assert.False(socket.Connected);

            if (!usePipe)
            {
                // In this case we can also verify if the stream is disposed
                Assert.Throws <ObjectDisposedException>(() => stream.Write(new byte[1]));
            }
        }
Beispiel #2
0
        public async Task Connection_CloseAsync_ClosesSocket(bool usePipe, ConnectionCloseMethod method)
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Connection connection = await factory.ConnectAsync(server.EndPoint);

            Stream stream = null;

            if (usePipe)
            {
                _ = connection.Pipe;
            }
            else
            {
                stream = connection.Stream;
            }

            connection.ConnectionProperties.TryGet(out Socket socket);

            await connection.CloseAsync(method);

            Assert.Throws <ObjectDisposedException>(() => socket.Send(new byte[1]));

            if (!usePipe) // No way to observe the stream if we work with the pipe
            {
                Assert.Throws <ObjectDisposedException>(() => stream.Write(new byte[1]));
            }
        }
Beispiel #3
0
        public async Task ConnectAsync_Success_SocketNoDelayIsTrue()
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(SocketType.Stream, ProtocolType.Tcp);
            using Connection connection            = await factory.ConnectAsync(server.EndPoint);

            connection.ConnectionProperties.TryGet(out Socket socket);
            Assert.True(socket.NoDelay);
        }
        public async Task ConnectAsync_TimedOut_ThrowsNetworkException()
        {
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint doesNotExist = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 23);

            // SocketError.TimedOut currently maps to SocketError.Unknown, so no asserion
            await Assert.ThrowsAsync <NetworkException>(() => factory.ConnectAsync(doesNotExist).AsTask());
        }
Beispiel #5
0
        public async Task Constructor3_ConnectAsync_Success_PropagatesConstructorArgumentsToSocket(EndPoint endPoint, SocketType socketType, ProtocolType protocolType)
        {
            endPoint         = RecreateUdsEndpoint(endPoint);
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, protocolType);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(endPoint.AddressFamily, socketType, protocolType);
            using Connection connection            = await factory.ConnectAsync(server.EndPoint);

            ValidateSocket(connection, socketType, protocolType, endPoint.AddressFamily);
        }
Beispiel #6
0
        public async Task Constructor2_ConnectAsync_Success_CreatesIPv6DualModeSocket()
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.IPv6Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(SocketType.Stream, ProtocolType.Tcp);
            using Connection connection            = await factory.ConnectAsync(server.EndPoint);

            Socket socket = ValidateSocket(connection, SocketType.Stream, ProtocolType.Tcp, AddressFamily.InterNetworkV6);

            Assert.True(socket.DualMode);
        }
Beispiel #7
0
        public async Task ConnectAsync_TimedOut_ThrowsNetworkException()
        {
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint doesNotExist = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 23);

            NetworkException ex = await Assert.ThrowsAsync <NetworkException>(() => factory.ConnectAsync(doesNotExist).AsTask());

            Assert.Equal(NetworkError.TimedOut, ex.NetworkError);
        }
Beispiel #8
0
        public async Task Connection_EndpointsAreCorrect(EndPoint endPoint, SocketType socketType, ProtocolType protocolType)
        {
            endPoint         = RecreateUdsEndpoint(endPoint);
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, protocolType);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(endPoint.AddressFamily, socketType, protocolType);
            using Connection connection            = await factory.ConnectAsync(server.EndPoint);

            // Checking for .ToString() result, because UnixDomainSocketEndPoint equality doesn't seem to be implemented
            Assert.Equal(server.EndPoint.ToString(), connection.RemoteEndPoint.ToString());
            Assert.IsType(endPoint.GetType(), connection.LocalEndPoint);
        }
Beispiel #9
0
        public async Task ConnectAsync_WhenHostNotFound_ThrowsNetworkException()
        {
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Unassigned as per https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt
            int         unusedPort = 8;
            DnsEndPoint endPoint   = new DnsEndPoint(System.Net.Test.Common.Configuration.Sockets.InvalidHost, unusedPort);

            NetworkException ex = await Assert.ThrowsAsync <NetworkException>(() => factory.ConnectAsync(endPoint).AsTask());

            Assert.Equal(NetworkError.HostNotFound, ex.NetworkError);
        }
Beispiel #10
0
        public async Task ConnectAsync_WhenRefused_ThrowsNetworkException()
        {
            using Socket notListening = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int port     = notListening.BindToAnonymousPort(IPAddress.Loopback);
            var endPoint = new IPEndPoint(IPAddress.Loopback, port);

            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            NetworkException ex = await Assert.ThrowsAsync <NetworkException>(() => factory.ConnectAsync(endPoint).AsTask());

            Assert.Equal(NetworkError.ConnectionRefused, ex.NetworkError);
        }
        public async Task Connection_Stream_FailingOperation_ThowsNetworkException()
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(SocketType.Stream, ProtocolType.Tcp);
            using Connection connection            = await factory.ConnectAsync(server.EndPoint);

            connection.ConnectionProperties.TryGet(out Socket socket);
            Stream stream = connection.Stream;

            socket.Dispose();

            Assert.Throws <NetworkException>(() => stream.Read(new byte[1], 0, 1));
            Assert.Throws <NetworkException>(() => stream.Write(new byte[1], 0, 1));
        }
        public async Task Connection_Pipe_FailingOperation_ThowsNetworkException()
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(SocketType.Stream, ProtocolType.Tcp);
            using Connection connection            = await factory.ConnectAsync(server.EndPoint);

            connection.ConnectionProperties.TryGet(out Socket socket);
            IDuplexPipe pipe = connection.Pipe;

            socket.Dispose();

            await Assert.ThrowsAsync <NetworkException>(() => pipe.Input.ReadAsync().AsTask());

            await Assert.ThrowsAsync <NetworkException>(() => pipe.Output.WriteAsync(new byte[1]).AsTask());
        }
Beispiel #13
0
        public async Task Connection_Pipe_ReadWrite_Success(EndPoint endPoint, SocketType socketType, ProtocolType protocolType)
        {
            endPoint         = RecreateUdsEndpoint(endPoint);
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, protocolType);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(endPoint.AddressFamily, socketType, protocolType);


            using Connection connection = await factory.ConnectAsync(server.EndPoint);

            IDuplexPipe pipe = connection.Pipe;

            byte[] sendData = { 1, 2, 3 };
            using MemoryStream receiveTempStream = new MemoryStream();

            await pipe.Output.WriteAsync(sendData);

            ReadResult rr = await pipe.Input.ReadAsync();

            // The test server should echo the data:
            Assert.True(rr.Buffer.FirstSpan.SequenceEqual(sendData));
        }
Beispiel #14
0
        public async Task Connection_Stream_ReadWrite_Success(EndPoint endPoint, SocketType socketType, ProtocolType protocolType)
        {
            endPoint         = RecreateUdsEndpoint(endPoint);
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, protocolType);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(endPoint.AddressFamily, socketType, protocolType);

            using Connection connection = await factory.ConnectAsync(server.EndPoint);

            Stream stream = connection.Stream;

            byte[] sendData    = { 1, 2, 3 };
            byte[] receiveData = new byte[sendData.Length];

            await stream.WriteAsync(sendData);

            await stream.FlushAsync();

            await stream.ReadAsync(receiveData);

            // The test server should echo the data:
            Assert.Equal(sendData, receiveData);
        }
Beispiel #15
0
        public async Task Connection_Pipe_ReadWrite_Integration(int totalLines)
        {
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            using SocketTestServer echoServer      = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);

            Socket serverSocket = null;

            echoServer.Accepted += s => serverSocket = s;

            using Connection connection = await factory.ConnectAsync(echoServer.EndPoint);

            IDuplexPipe pipe = connection.Pipe;

            ConcurrentQueue <string> linesSent = new ConcurrentQueue <string>();
            Task writerTask = Task.Factory.StartNew(async() =>
            {
                byte[] endl = Encoding.ASCII.GetBytes("\n");
                StringBuilder expectedLine = new StringBuilder();

                for (int i = 0; i < totalLines; i++)
                {
                    int words = i % 10 + 1;
                    for (int j = 0; j < words; j++)
                    {
                        string word = Guid.NewGuid() + " ";
                        Encoding.ASCII.GetBytes(word, pipe.Output);
                        expectedLine.Append(word);
                    }
                    linesSent.Enqueue(expectedLine.ToString());
                    await pipe.Output.WriteAsync(endl);
                    expectedLine.Clear();
                }

                await pipe.Output.FlushAsync();

                // This will also trigger completion on the reader. TODO: Fix
                // await pipe.Output.CompleteAsync();
            }, TaskCreationOptions.LongRunning);

            // The test server should echo the data sent to it

            PipeReader reader = pipe.Input;

            int lineIndex = 0;

            void ProcessLine(ReadOnlySequence <byte> lineBuffer)
            {
                string line = Encoding.ASCII.GetString(lineBuffer);

                Assert.True(linesSent.TryDequeue(out string expectedLine));
                Assert.Equal(expectedLine, line);
                lineIndex++;

                // Received everything, shut down the server, so next read will complete:
                if (lineIndex == totalLines)
                {
                    serverSocket.Shutdown(SocketShutdown.Both);
                }
            }

            while (true)
            {
                try
                {
                    ReadResult result = await reader.ReadAsync();

                    ReadOnlySequence <byte> buffer   = result.Buffer;
                    SequencePosition?       position = null;

                    // Stop reading if there's no more data coming
                    if (result.IsCompleted)
                    {
                        break;
                    }

                    do
                    {
                        // Look for a EOL in the buffer
                        position = buffer.PositionOf((byte)'\n');

                        if (position != null)
                        {
                            // Process the line
                            ProcessLine(buffer.Slice(0, position.Value));

                            // Skip the line + the \n character (basically position)
                            buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
                        }
                    }while (position != null);

                    // Tell the PipeReader how much of the buffer we have consumed
                    reader.AdvanceTo(buffer.Start, buffer.End);
                }
                catch (SocketException)
                {
                    // terminate
                }
            }

            // Mark the PipeReader as complete
            await reader.CompleteAsync();

            await writerTask;

            // TODO: If this is done in the end of writerTask the socket stops working
            Assert.Equal(totalLines, lineIndex);
        }
Beispiel #16
0
 public void ConnectAsync_NullEndpoint_ThrowsArgumentNullException()
 {
     using SocketsConnectionFactory factory = new SocketsConnectionFactory(SocketType.Stream, ProtocolType.Tcp);
     Assert.ThrowsAsync <ArgumentNullException>(() => factory.ConnectAsync(null).AsTask());
 }
Beispiel #17
0
        public async Task ConnectAsync_WhenCancelledBeforeInvocation_ThrowsTaskCancelledException()
        {
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint doesNotExist = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 23);

            CancellationToken cancellationToken = new CancellationToken(true);

            OperationCanceledException ex = await Assert.ThrowsAsync <OperationCanceledException>(() => factory.ConnectAsync(doesNotExist, cancellationToken : cancellationToken).AsTask());

            Assert.Equal(cancellationToken, ex.CancellationToken);
        }