简体   繁体   English

C#使用TCP读取IP摄像机的所有数据

[英]C# Read all data form IP camera using TCP

I have IP camera and I have problem to read image data from this camera. 我有IP摄像机,但无法从此摄像机读取图像数据。 To read image I have to send command to camera and read: 1) Length Of Telegram 2) Response ID Get Image 3) Error Code 4) Image type 5) Image results 6) Number of rows, columns 7) Image data 要读取图像,我必须向相机发送命令并读取:1)电报长度2)响应ID获取图像3)错误代码4)图像类型5)图像结果6)行数,列数7)图像数据

To read data form point 1 to 6 is no problem because this is only 14 bytes. 从点1到6读取数据没有问题,因为这只有14个字节。 In point 6 I read the size of image. 在第6点中,我读取了图像的大小。 For example let number of rows and columns will be 640x480 so we have 307200 bytes. 例如,让行和列的数量为640x480,因此我们有307200字节。

To read image I am using Visual Studio 2010 and WindowsForm Application and action form button: 要读取图像,我正在使用Visual Studio 2010和WindowsForm应用程序以及操作表单按钮:

private void butReadImage_Click(object sender, EventArgs e)
{
     // code to read data from point 1 to 6
     // start read data image (point 7)

}

In butReadImage_Click I can read only 7000 bytes of image data because camera do not send all image data in one package. butReadImage_Click我只能读取7000字节的图像数据,因为相机不会在一个包中发送所有图像数据。 To read all data I enable timer (1ms interval) in butReadImage_Click an then using 为了读取所有数据,我在butReadImage_Click启用了计时器(间隔为1ms),然后使用

     private void timReadImage_Tick(object sender, EventArgs e)
     {
            // read rest data form camera, about two data packets
            int numberOfBytesRead;
            while (rwSensorStream.DataAvailable)
            {
                numberOfBytesRead = rwSensorStream.Read(BinaryImageData_Byte_14_n, 0, BinaryImageData_Byte_14_n.Length);
                tempRC = tempRC + numberOfBytesRead;

                for (int i = 0; i < numberOfBytesRead; i++)
                {
                    image.Add(BinaryImageData_Byte_14_n[i]);
                }
            }
     }

I now that this is bad code using Timer. 我现在这是使用Timer的错误代码。 Does anyone have an idea how to read all data sent in several packages?. 有谁知道如何读取以多个包发送的所有数据?

Read the data asynchronously. 异步读取数据。 You will have to figure out what the while loop conditional should be to loop the correct number of times for a single image, but awaiting ReadAsync to get data from your stream will allow your code to wait for a complete transmission before continuing. 您必须弄清楚while循环的条件应该是为单个图像循环正确的次数,但是等待ReadAsync从流中获取数据将使您的代码在继续之前等待完整的传输。

public async Task getData(NetworkStream rwSensorStream) {
    while (true) {
        byte[ ] buffer = new byte[numberOfBytesAtOnce];
        int read = await rwSensorStream.ReadAsync(buffer, 0, buffer.Length); 
        //wait for next package

        if (read > 0) {
          // data received, process it 
        } 
        else break;  // will occur when connection is broken
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM