如何使用异步套接字通过TCP发送图像

时间:2019-06-04 12:39:43

标签: c# .net wpf sockets

因此,我昨天试图通过TCP Socket Client将文件发送到服务器,我很快意识到您一次不能发送超过65k字节的数据。

自从我尝试发送一个260k字节的图像以来,这很快就成为一个问题。

所以我的思考过程就是这样。

首先,我将发送一个包含图像大小的数据包,以便服务器随后知道要读取多少,然后在下一步中,我将开始发送图像中的所有字节。

由于我正在处理异步套接字,因此在发送第一个数据包之后,它并不是真正的等待或阻塞。

所以我不知道如何首先发送size,所以我知道要读取多少然后实际开始读取数据,因为我必须从1024的服务器中分块发送数据每个块的字节数

这是我在Client

中所做的
var BUFFER = new byte[1024];
                    //Set the BUFFER Type
                    BUFFER[0] = 2;

//This just returns the image path from a image on the desktop.
                    var ImageBuffer = ImageHelper.GetImage();
                    var IMAGE_SIZE_BUFFER = BitConverter.GetBytes(ImageBuffer.Length);

                    Buffer.BlockCopy(IMAGE_SIZE_BUFFER, 0, BUFFER, 1, IMAGE_SIZE_BUFFER.Length);


                    CLIENT_SOCKET.Send(BUFFER, 0, BUFFER.Length,
                        SocketFlags.None);

在服务器上,我正在这样做

        var BUFFER_SIZE = CLIENT_SOCKET.EndReceive(ar);

        //Create a packet that has the length of the BUFFER_SIZE
        var PACKET = new byte[BUFFER_SIZE];

        //Copy over the content from the RECEIVED_BUFFER[] to the PACKET[] from 0 to PACKET.Length.
        Array.Copy(RECEIVED_BUFFER, PACKET, PACKET.Length);

        //Determine the packet Type by reading the first byte of the array.
        var PACKET_TYPE = RECEIVED_BUFFER[0];

        //Interpret the actual data skipping the first byte since that's the type.
        var ACTUAL_PACKET = RECEIVED_BUFFER.Skip(1);

        //Check what type of packet we received.
        switch (PACKET_TYPE)
        {

            case 1:
                break;

            //Image Send
            case 2:
                //stores the int value of the packet size
                var packetSize = BitConverter.ToInt32(ACTUAL_PACKET.ToArray(),0);
                //Receive the first packet & block


                //Start receiving the second packet. (Keep reading until it hit the size of the variable)
                //This is where I get stuck
                break;

        }

        //Begin receiving data again
        CLIENT_SOCKET.BeginReceive(RECEIVED_BUFFER, 0, RECEIVED_BUFFER.Length, SocketFlags.None,
            ReceivedDataCallback, CLIENT_SOCKET);

0 个答案:

没有答案