Click here to Skip to main content
15,881,600 members
Articles / Programming Languages / C#

Sending Files using TCP

Rate me:
Please Sign up or sign in to vote.
4.43/5 (25 votes)
18 Jan 2009CPOL4 min read 359.9K   40.3K   107   57
Sending files using TCP

Introduction 

A socket is an abstraction through which an application may send and receive data, in pretty much the same way as opening a file to read and write data. Different types of sockets correspond to different protocols. I will give you a brief description of TCP/IP protocol which has the main types of stream sockets and datagram sockets. Stream sockets use TCP and datagram sockets use UDP.

The .NET Framework has two classes for TCP which are TCPClient and TCPListener. A TCPClient initiates the communication with a server which is waiting for the connection. TCP is connection oriented and UDP is connectionless, which means that UDP sockets do not need to be connected before being used. Another difference between TCP and UDP is that there is no guarantee that a message sent via a UDP socket will arrive at its destination, and messages can be delivered in a different order than they were sent.

You have to carefully choose when you want to use TCP and when UDP. When you are sending a small amount of data, using TCP might double number of messages being sent and UDP provides minimal overhead platform.

Here I am going to show you a server/client application, by which you can send files using TCP.

Using the Code 

Let’s talk about the client application first. The client application consists of an OpenFileDialog for selecting the file you want to send, two text boxes to enter server IP address and server port number, a label which show you the status of your application such as connected to the server or number of bytes that have been sent, a progress bar, and a button named send which sends data to the server.

When you are connected via TCP you create a network stream which you can read and write in, similar to all other streams you worked with. Writing a large amount of data to the stream is not a good idea, so I break the selected file into smaller packets in which each packet length is 1024 bytes (1KB) and then send all the packets to the server. The SendTCP function is as follows:

C#
public void SendTCP(string M, string IPA, Int32 PortN)
{
    byte[] SendingBuffer = null
    TcpClient client = null;
    lblStatus.Text = "";
    NetworkStream netstream = null;
    try
    {
         client = new TcpClient(IPA, PortN);
         lblStatus.Text = "Connected to the Server...\n";
         netstream = client.GetStream();
         FileStream Fs = new FileStream(M, FileMode.Open, FileAccess.Read);
         int NoOfPackets = Convert.ToInt32
	  (Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(BufferSize)));
         progressBar1.Maximum = NoOfPackets;
         int TotalLength = (int)Fs.Length, CurrentPacketLength, counter = 0;
         for (int i = 0; i < NoOfPackets; i++)
         {
             if (TotalLength > BufferSize)
             {
                 CurrentPacketLength = BufferSize;
                 TotalLength = TotalLength - CurrentPacketLength;
             }
             else
                 CurrentPacketLength = TotalLength;
                 SendingBuffer = new byte[CurrentPacketLength];
                 Fs.Read(SendingBuffer, 0, CurrentPacketLength);
                 netstream.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
                 if (progressBar1.Value >= progressBar1.Maximum)
                      progressBar1.Value = progressBar1.Minimum;
                 progressBar1.PerformStep();
             }
                
             lblStatus.Text=lblStatus.Text+"Sent "+Fs.Length.ToString()+" 
						bytes to the server";
             Fs.Close();
         }
    catch (Exception ex)
    {
         Console.WriteLine(ex.Message);
    }
    finally
    {
         netstream.Close();
         client.Close();
    }
} 

As you can see, a TCP client and a network stream are being constructed and a network connection is initiated. After opening the selected file according to the buffer size which is 1024 bytes, the number of packets that are going to be sent is calculated. There are two other variables CurrentPacketLength and TotalLength. If the total length of the selected file is more than the buffer size the CurrentPacketLength is set to the buffer size, otherwise why send some empty bytes, so CurrentPacketLength is set to the total length of the file. After that, I subtract the current from the total length, so actually we can say total length is showing the total amount of data that has not been sent yet. The rest is pretty much straight forward, reading the data from the file stream and writing it to the SendingBuffer according to the CurrentPacketLength and writing the buffer to the network stream. After all packets have been sent, the status will show the amount of bytes you have sent to the server.

At the server side, the application is listening for an incoming connection:

C#
public void ReceiveTCP(int portN)
{
    TcpListener Listener = null;
    try
    {
        Listener = new TcpListener(IPAddress.Any, portN);
        Listener.Start();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    byte[] RecData = new byte[BufferSize];
    int RecBytes;

    for (; ; )
    {
        TcpClient client = null;
        NetworkStream netstream = null;
        Status = string.Empty;
        try
        {                          
             string message = "Accept the Incoming File ";
             string caption = "Incoming Connection";
             MessageBoxButtons buttons = MessageBoxButtons.YesNo;
             DialogResult result;

             if (Listener.Pending())
             {
                  client = Listener.AcceptTcpClient();
                  netstream = client.GetStream();
                  Status = "Connected to a client\n";
                  result = MessageBox.Show(message, caption, buttons);

                  if (result == System.Windows.Forms.DialogResult.Yes)
                  {
                       string SaveFileName=string.Empty;
                       SaveFileDialog DialogSave = new SaveFileDialog();
                       DialogSave.Filter = "All files (*.*)|*.*";
                       DialogSave.RestoreDirectory = true;
                       DialogSave.Title = "Where do you want to save the file?";
                       DialogSave.InitialDirectory = @"C:/";
                       if (DialogSave.ShowDialog() == DialogResult.OK)
                            SaveFileName = DialogSave.FileName;
                       if (SaveFileName != string.Empty)
                       {
                           int totalrecbytes = 0;
                           FileStream Fs = new FileStream
			(SaveFileName, FileMode.OpenOrCreate, FileAccess.Write);
                           while ((RecBytes = netstream.Read
				(RecData, 0, RecData.Length)) > 0)
                           {
                                Fs.Write(RecData, 0, RecBytes);
                                totalrecbytes += RecBytes;
                           }
                           Fs.Close();
                       }
                       netstream.Close();
                       client.Close();
                  }
             }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            //netstream.Close();
        }
    }
}

A TCP listener is created and starts listening to the specified port. Again the buffer size is set to 1024 bytes. A TCP listener can pre check to see if there are any connections pending before calling the AcceptTcpClient method. It returns true if there are any pending connections. This method is a good way of avoiding the socket being blocked. Before reading anything from the network stream, a message box asks you if you want to accept the incoming connection, then a SaveFileDialog will be opened, and when you enter the file name plus extension, a file stream will be constructed and you start reading from the network stream and writing to the file stream. Create a thread in your code and run the receiving method in the created thread. I have sent more than 100 MB files in a LAN with the application.

History

  • 18th January, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionfile not receiving Pin
Member 1474357924-Sep-20 21:22
Member 1474357924-Sep-20 21:22 
QuestionUnable to send file " Progress bar freezes" and file did not saved in partition c after accept connection. Pin
Member 1486153016-Jun-20 0:19
Member 1486153016-Jun-20 0:19 
Questionloss data when i sent file Pin
Member 1480716420-Apr-20 0:18
Member 1480716420-Apr-20 0:18 
GeneralMy vote of 5 Pin
macleo_cn6-Mar-19 0:05
macleo_cn6-Mar-19 0:05 
GeneralMy vote of 5 Pin
macleo_cn5-Mar-19 19:58
macleo_cn5-Mar-19 19:58 
QuestionClosing connection Pin
Member 1362821217-Jan-18 7:24
Member 1362821217-Jan-18 7:24 
Generalsocket Pin
Member 1323964230-Jun-17 5:20
Member 1323964230-Jun-17 5:20 
Questionthe files were not received Pin
Member 1306012124-May-17 1:35
Member 1306012124-May-17 1:35 
AnswerRe: the files were not received Pin
Margaret Sitati14-May-19 7:56
Margaret Sitati14-May-19 7:56 
Questionnull refrence exception Pin
Member 1039285723-Mar-17 22:02
professionalMember 1039285723-Mar-17 22:02 
QuestionNULL Exception thrown Pin
Member 124954037-May-16 3:49
Member 124954037-May-16 3:49 
AnswerRe: NULL Exception thrown Pin
iadol9-Jul-16 17:27
iadol9-Jul-16 17:27 
QuestionFor debugging Pin
robertkjr3d20-Mar-16 13:19
robertkjr3d20-Mar-16 13:19 
QuestionHow to ascertain the real filename? Pin
robertkjr3d20-Mar-16 13:10
robertkjr3d20-Mar-16 13:10 
AnswerRe: How to ascertain the real filename? Pin
robertkjr3d20-Mar-16 13:15
robertkjr3d20-Mar-16 13:15 
GeneralRe: How to ascertain the real filename? Pin
Garth J Lancaster20-Mar-16 14:12
professionalGarth J Lancaster20-Mar-16 14:12 
Questionsave dialog box is not showing up Pin
Member 1208498625-Oct-15 0:21
Member 1208498625-Oct-15 0:21 
QuestionI got a memory disruption! Pin
Member 1205868814-Oct-15 8:02
Member 1205868814-Oct-15 8:02 
GeneralMy vote of 5 Pin
edarkzero23-Jun-15 14:43
edarkzero23-Jun-15 14:43 
QuestionSave dialog was not open Pin
chengji1810-Nov-14 3:23
chengji1810-Nov-14 3:23 
AnswerRe: Save dialog was not open Pin
FilipRooms22-Jun-15 3:00
FilipRooms22-Jun-15 3:00 
GeneralRe: Save dialog was not open Pin
Member 1208498625-Oct-15 0:31
Member 1208498625-Oct-15 0:31 
GeneralRe: Save dialog was not open Pin
Member 146440284-Nov-19 7:06
Member 146440284-Nov-19 7:06 
QuestionDoes the code Works On Internet? Pin
agent_kruger9-Jul-14 1:07
professionalagent_kruger9-Jul-14 1:07 
QuestionAmir Hesami Pin
Member 1075099518-May-14 23:23
Member 1075099518-May-14 23:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.