我一直在尝试将网络流读入数组。下面的代码运行良好,但速度非常慢:
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 BytesEnd函数
谢谢你的帮助。
发布于 2021-07-08 05:27:03
代码的问题是,每次调整数组的大小时,数组实际上也会被复制。这段代码应该可以解决你的问题:
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 Functionhttps://stackoverflow.com/questions/68293151
复制相似问题