将NetworkStream读取到阵列中



我一直在尝试将网络流读取到数组中。下面的代码运行良好,但速度非常慢:

Private Function ReadBytes(ByVal NetworkStream As System.Net.Sockets.NetworkStream) As Byte()
Dim Bytes As Byte() = {}
Dim Index As Integer = 0
While NetworkStream.DataAvailable = True
Array.Resize(Bytes, Index + 1)
Bytes(Index) = NetworkStream.ReadByte()
Index += 1
End While
Return Bytes

终端功能

谢谢你的帮助。

代码的问题是,每次调整数组的大小时,实际上也会复制数组。这个代码应该可以解决你的问题:

Private Function ReadBytes(ByVal NetworkStream As System.Net.Sockets.NetworkStream) As Byte()
Dim BlockSize As Integer = 65536
Dim Bytes(BlockSize) As Byte
Dim Position As Integer = 0
Dim DataRead As Integer = 0
Do
ReDim Preserve Bytes(Position + BlockSize)
DataRead = NetworkStream.Read(Bytes, Position, BlockSize)
Position += BlockSize
If DataRead = 0 Then
For i = Bytes.Length - 1 To 0 Step -1
If Not Bytes(i) = 0 Then
ReDim Preserve Bytes(i)
Exit Do
End If
Next
Exit Do
End If
Loop
Return Bytes
End Function

最新更新