将 networkstream.Read 中的所有字节放入单字节数组

Get all the bytes from networkstream.Read into single byte array

我有一个 TCP 服务器(一个线扫描相机),它根据规范向我发送图像数据。图像数据采用一维字节数组的形式。相机发送的字节数是已知的,但它会根据规范而变化,因此有时会很大,有时会很小。我正在使用 Networkstream.Read 获取字节并尝试将其存储到数组中。

问题是它以数据包的形式发送给我。我需要一种方法,将从流发送的所有数据存储在一个字节数组中,然后我可以使用它并将其转换为图像。

这是我现在一直在使用的代码。我还是 VB 的新手。我尝试将数据存储到数组中,然后附加它们,但不知何故 VB 不提供该功能。

        Dim imageData(numberOfColumns * numberOfLines - 1) As Byte
        Dim bytesReceived = 
        Dim bytesReceivedTotal = 0
        Dim bytesToRcv = numberOfColumns * numberOfLines
        Dim imageFragment() As Byte
        Dim rcvbytes(8092) As Byte 'tried socket.receivebuffersize too
        Dim readCount = 0

        Do
            bytesReceived = clientStream.Read(rcvbytes, 0, rcvbytes.Length) 
            bytesReceivedTotal += bytesReceived
            rcvbytes.CopyTo(imageData, (bytesReceivedTotal - bytesReceived))
        Loop Until bytesReceivedTotal = bytesToRcv

此代码的问题是 rcvbytes 的长度不会因上次读取而改变。有没有一种方法可以将流中的所有数据存储在一个字节数组中?服务器发送的字节大小通过以下方式获得:(numberOfLines * numberOfColumns)

更新#2:工作代码

            Do
            Dim bytesWanted As Integer = bytesReceivedTotal + 8092
            Dim bytesToRead As Integer = If(bytesWanted > imageData.Length, imageData.Length - bytesReceivedTotal, 8092)


            bytesReceived = clientStream.Read(imageData, bytesReceivedTotal, bytesToRead)
            bytesReceivedTotal += bytesReceived
        Loop Until bytesReceivedTotal = bytesToRcv

由于 TCP 是一种基于流的协议,因此确保将所有预期数据(整个 "message")放入单个数组的唯一方法是继续调用 NetworkStream.Read() 直到您阅读足够的字节数。

I tried storing the data into arrays and then append them but somehow VB does not provide that functionality.

事实并非如此。有几种方法可以连接数据块。例如,您可以使用 List(Of T).

但是在您的情况下,答案实际上就在您的眼皮底下。如果您查看 NetworkStream.Read() documentation,您会发现第二个参数(称为 offset)指定 "The location in buffer to begin storing the data to" - 其中 buffer是您指定为第一个参数的字节数组。

如果您为 offset 参数提供已读取字节数,它将在数组中将新字节追加到已接收字节之后。另请记住,如果您接近数组末尾,您不想阅读太多内容。

Dim bytesWanted As Integer = bytesReceivedTotal + 8092
Dim bytesToRead As Integer = If(bytesWanted > imageData.Length, imageData.Length - bytesReceivedTotal, 8092)

clientStream.Read(imageData, bytesReceivedTotal, bytesToRead)