Ejemplo n.º 1
0
        public async Task ServerResponse_WriteRead_RoundtripsProperly()
        {
            // Arrange
            var response     = new CompletedServerResponse(42, utf8output: false, output: "a string", error: "an error");
            var memoryStream = new MemoryStream();

            // Act
            await response.WriteAsync(memoryStream, CancellationToken.None);

            // Assert
            Assert.True(memoryStream.Position > 0);
            memoryStream.Position = 0;
            var result = (CompletedServerResponse)await ServerResponse.ReadAsync(memoryStream, CancellationToken.None);

            Assert.Equal(42, result.ReturnCode);
            Assert.False(result.Utf8Output);
            Assert.Equal("a string", result.Output);
            Assert.Equal("an error", result.ErrorOutput);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// May throw exceptions if there are pipe problems.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task <ServerResponse> ReadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
        {
            ServerLogger.Log("Reading response length");
            // Read the response length
            var lengthBuffer = new byte[4];
            await ServerProtocol.ReadAllAsync(stream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false);

            var length = BitConverter.ToUInt32(lengthBuffer, 0);

            // Read the response
            ServerLogger.Log("Reading response of length {0}", length);
            var responseBuffer = new byte[length];
            await ServerProtocol.ReadAllAsync(
                stream,
                responseBuffer,
                responseBuffer.Length,
                cancellationToken)
            .ConfigureAwait(false);

            using (var reader = new BinaryReader(new MemoryStream(responseBuffer), Encoding.Unicode))
            {
                var responseType = (ResponseType)reader.ReadInt32();

                switch (responseType)
                {
                case ResponseType.Completed:
                    return(CompletedServerResponse.Create(reader));

                case ResponseType.MismatchedVersion:
                    return(new MismatchedVersionServerResponse());

                case ResponseType.Shutdown:
                    return(ShutdownServerResponse.Create(reader));

                case ResponseType.Rejected:
                    return(new RejectedServerResponse());

                default:
                    throw new InvalidOperationException("Received invalid response type from server.");
                }
            }
        }