From 751ac19c4b21da8a7f11006ed00e47e4e4156783 Mon Sep 17 00:00:00 2001 From: Christian Date: Fri, 26 Jan 2018 21:25:56 +0100 Subject: [PATCH] Fix reading more data than required for the body. --- .../MQTTnet.NetStandard/Adapter/MqttChannelAdapter.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Frameworks/MQTTnet.NetStandard/Adapter/MqttChannelAdapter.cs b/Frameworks/MQTTnet.NetStandard/Adapter/MqttChannelAdapter.cs index 76ac050..4b8bafd 100644 --- a/Frameworks/MQTTnet.NetStandard/Adapter/MqttChannelAdapter.cs +++ b/Frameworks/MQTTnet.NetStandard/Adapter/MqttChannelAdapter.cs @@ -142,7 +142,13 @@ namespace MQTTnet.Adapter var buffer = new byte[ReadBufferSize]; while (body.Length < header.BodyLength) { - var readBytesCount = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + 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) @@ -150,6 +156,8 @@ namespace MQTTnet.Adapter 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); }