sending a large amount of data throught TCP socket

12,657

There are lots of different solutions but chunking is usually a good solution, you can either do this blindly where you keep filling your temporary buffer and then putting it into some stateful buffer until you hit some arbitrary token or the buffer is not completely full, or you can adhere to some sort of contract per tcp message (a message being the overall data to recieve).

If you were to look at doing some sort of contract then do something like the first N bytes of a message is the descriptor, which you could make as big or as small as you want, but your temp buffer will ONLY read this size up front from the stream.

A typical header could be something like:

public struct StreamHeader // 5 bytes
{
   public byte MessageType {get;set;} // 1 byte
   public int MessageSize {get;set;}  // 4 bytes
}

So you would read that in then if its small enough allocate the full message size to the temp buffer and read it all in, or if you deem it too big chunk it into sections and keep reading until the total bytes you have received match the MessageSize portion of your header structure.

Share:
12,657
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    This is my first question posted on this forum, and I'm a beginner in c# world , so this is kind of exciting for me, but I'm facing some issues with sending a large amount of data through sockets so this is more details about my problem:

    I'm sending a binary image of 5 Mo through a TCP socket, at the receiving part I'm saving the result(data received ) and getting only 1.5 Mo ==> data has been lost (I compared the original and the resulting file and it showed me the missed parts) this is the code I use:

    private void senduimage_Click(object sender, EventArgs e)
    {
        if (!user.clientSocket_NewSocket.Connected)
        {
            Socket clientSocket_NewSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            user.clientSocket_NewSocket = clientSocket_NewSocket;
            System.IAsyncResult _NewSocket = user.clientSocket_NewSocket.BeginConnect(ip_address, NewSocket.Transceiver_TCP_Port, null, null);
            bool successNewSocket = _NewSocket.AsyncWaitHandle.WaitOne(2000, true);
         }
         byte[] outStream = System.Text.Encoding.ASCII.GetBytes(Uimage_Data);
         user.clientSocket_NewSocket.Send(outStream);
     }
    

    In forums they say to divide data into chunks, is this a solution, if so how can I do this, I've tried but it didn't work!