Skip to content

Commit

Permalink
fix: 当无法一次读取完所有数据时下一次读取会出现数据错乱
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Aug 13, 2024
1 parent 6e30275 commit c8836e0
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions Network/RsaStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,10 @@ public override int Read(byte[] buffer, int offset, int count)
{
if (this.pendingBytes != null && this.pendingBytes.Length != 0)
{
(byte[] temp, this.pendingBytes) = (this.pendingBytes[0..count], this.pendingBytes[count..]);
int actualSize = Math.Min(this.pendingBytes.Length, count);
(byte[] temp, this.pendingBytes) = (this.pendingBytes[0..actualSize], this.pendingBytes[actualSize..]);
Array.Copy(temp, 0, buffer, offset, count);
return actualSize;
}

if (buffer == null) throw new ArgumentNullException(nameof(buffer));
Expand All @@ -168,6 +170,7 @@ public override int Read(byte[] buffer, int offset, int count)
long messageLength = BitConverter.ToInt64(messageLengthByte);
byte[] restBytes = new byte[Math.Max(0, messageLength - count)];
long actualSize = Math.Min(messageLength, count);
int copySize = 0;

while ((bytesRead = _stream.Read(encryptedBuffer, 0, encryptedBlockSize)) > 0)
{
Expand All @@ -178,18 +181,17 @@ public override int Read(byte[] buffer, int offset, int count)

if (decryptedBlock.Length > 0)
{
int copySize = Math.Min(decryptedBlock.Length, count - totalBytesRead);
copySize = Math.Min(decryptedBlock.Length, count - totalBytesRead);
Array.Copy(decryptedBlock, 0, buffer, offset + totalBytesRead, copySize);
totalBytesRead += copySize;
totalBytesRead += decryptedBlock.Length;
}

if (totalBytesRead >= actualSize)
break;
}
if (totalBytesRead > actualSize)
{
this.pendingBytes = new byte[totalBytesRead - actualSize];
Array.Copy(decryptedBlock[0..(int)(totalBytesRead - actualSize)], this.pendingBytes, (totalBytesRead - actualSize));
Array.Copy(decryptedBlock[copySize..(int)(copySize + totalBytesRead - actualSize)], restBytes, (totalBytesRead - actualSize));
}
if (totalBytesRead < actualSize &&
restBytes.Length != 0 &&
Expand Down

0 comments on commit c8836e0

Please sign in to comment.