Ejemplo n.º 1
0
        public void MqttPacketReader_EmptyStream()
        {
            var memStream = new MemoryStream();
            var header    = MqttPacketReader.ReadHeaderAsync(memStream, CancellationToken.None).GetAwaiter().GetResult();

            Assert.IsNull(header);
        }
Ejemplo n.º 2
0
        private static async Task <ReceivedMqttPacket> ReceiveAsync(Stream stream, CancellationToken cancellationToken)
        {
            var header = await MqttPacketReader.ReadHeaderAsync(stream, cancellationToken).ConfigureAwait(false);

            if (header == null)
            {
                return(null);
            }

            if (header.BodyLength == 0)
            {
                return(new ReceivedMqttPacket(header, new MemoryStream(new byte[0], false)));
            }

            var body = header.BodyLength <= ReadBufferSize ? new MemoryStream(header.BodyLength) : new MemoryStream();

            var buffer = new byte[ReadBufferSize];

            while (body.Length < header.BodyLength)
            {
                var bytesLeft = header.BodyLength - (int)body.Length;
                if (bytesLeft > buffer.Length)
                {
                    bytesLeft = buffer.Length;
                }

                var readBytesCount = await stream.ReadAsync(buffer, 0, bytesLeft, cancellationToken).ConfigureAwait(false);

                // Check if the client closed the connection before sending the full body.
                if (readBytesCount == 0)
                {
                    throw new MqttCommunicationException("Connection closed while reading remaining packet body.");
                }

                // Here is no need to await because internally only an array is used and no real I/O operation is made.
                // Using async here will only generate overhead.
                body.Write(buffer, 0, readBytesCount);
            }

            body.Seek(0L, SeekOrigin.Begin);

            return(new ReceivedMqttPacket(header, body));
        }
Ejemplo n.º 3
0
        private static void DeserializeAndCompare(MqttBasePacket packet, string expectedBase64Value)
        {
            var serializer = new MqttPacketSerializer();

            var buffer1 = serializer.Serialize(packet);

            using (var headerStream = new MemoryStream(Join(buffer1)))
            {
                var header = MqttPacketReader.ReadHeaderAsync(headerStream, CancellationToken.None).GetAwaiter().GetResult();

                using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, header.BodyLength))
                {
                    var deserializedPacket = serializer.Deserialize(header, bodyStream);
                    var buffer2            = serializer.Serialize(deserializedPacket);

                    Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Join(buffer2)));
                }
            }
        }