@@ -37,11 +37,41 @@ public IpcReader(Stream stream, IIpcMessageSerializer serializer, bool leaveOpen
37
37
38
38
private async Task < byte [ ] > ReadMessageAsync ( CancellationToken cancellationToken )
39
39
{
40
- await _stream . ReadAsync ( _lengthBuffer , 0 , _lengthBuffer . Length , cancellationToken ) . ConfigureAwait ( false ) ;
41
- int length = _lengthBuffer [ 0 ] | _lengthBuffer [ 1 ] << 8 | _lengthBuffer [ 2 ] << 16 | _lengthBuffer [ 3 ] << 24 ;
40
+ int headerLength = await _stream . ReadAsync ( _lengthBuffer , 0 , _lengthBuffer . Length , cancellationToken ) ;
42
41
43
- byte [ ] bytes = new byte [ length ] ;
44
- await _stream . ReadAsync ( bytes , 0 , length , cancellationToken ) . ConfigureAwait ( false ) ;
42
+ if ( headerLength != 4 )
43
+ {
44
+ throw new ArgumentOutOfRangeException ( $ "Header length must be 4 but was { headerLength } ") ;
45
+ }
46
+
47
+ int expectedLength = _lengthBuffer [ 0 ] | _lengthBuffer [ 1 ] << 8 | _lengthBuffer [ 2 ] << 16 | _lengthBuffer [ 3 ] << 24 ;
48
+ byte [ ] bytes = new byte [ expectedLength ] ;
49
+ int totalBytesReceived = 0 ;
50
+ int remainingBytes = expectedLength ;
51
+
52
+ using ( var ms = new MemoryStream ( ) )
53
+ {
54
+ while ( totalBytesReceived < expectedLength )
55
+ {
56
+ int dataLength = await _stream . ReadAsync ( bytes , 0 , remainingBytes , cancellationToken ) ;
57
+
58
+ if ( dataLength == 0 )
59
+ {
60
+ break ; // end of stream or stream shut down.
61
+ }
62
+
63
+ ms . Write ( bytes , 0 , dataLength ) ;
64
+ totalBytesReceived += dataLength ;
65
+ remainingBytes -= dataLength ;
66
+ }
67
+
68
+ bytes = ms . ToArray ( ) ;
69
+ }
70
+
71
+ if ( totalBytesReceived != expectedLength )
72
+ {
73
+ throw new System . ArgumentOutOfRangeException ( $ "Data length must be { expectedLength } but was { totalBytesReceived } ") ;
74
+ }
45
75
46
76
return bytes ;
47
77
}
0 commit comments