将数据从网络流读取到阵列中



是否有更好的方法将数据从网络流读取到数组中。以下代码有效,但接收大量数据需要一段时间:

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
End Function

感谢您提前提供的帮助。

查看文档,这是我想到的(未测试(:

Private Sub ReadBytes(ByRef Bytes() As Byte, ByRef NetworkStream As System.Net.Sockets.NetworkStream)
Dim nBr, u As Integer ' nBr = nr. of bytes read 
u = -1
Dim L% = 1024 'increase this number to get better performance

While NetworkStream.DataAvailable
ReDim Preserve Bytes(u + L)
nBr = NetworkStream.Read(Bytes, u + 1, L)
u += nBr
If nBr < L Then ReDim Preserve Bytes(u)

End While
End Sub

注意:传递大数组ByRef而不是Function result,以避免不必要的内存复制。

最新更新