从网络流中读取数据到数组
Read data from networkstream into array
是否有更好的方法将数据从网络流读取到数组中。以下代码可以运行,但是接收大量数据需要一段时间:
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 结果,以避免不必要的内存复制。
是否有更好的方法将数据从网络流读取到数组中。以下代码可以运行,但是接收大量数据需要一段时间:
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 结果,以避免不必要的内存复制。