Click here to Skip to main content
13,291,254 members (59,530 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


102 bookmarked
Posted 18 Jan 2009

Sending Files using TCP

, 18 Jan 2009
Rate this:
Please Sign up or sign in to vote.
Sending files using TCP


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:

public void SendTCP(string M, string IPA, Int32 PortN)
    byte[] SendingBuffer = null
    TcpClient client = null;
    lblStatus.Text = "";
    NetworkStream netstream = null;
         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;
                 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;
             lblStatus.Text=lblStatus.Text+"Sent "+Fs.Length.ToString()+" 
						bytes to the server";
    catch (Exception ex)

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:

public void ReceiveTCP(int portN)
    TcpListener Listener = null;
        Listener = new TcpListener(IPAddress.Any, portN);
    catch (Exception ex)

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

    for (; ; )
        TcpClient client = null;
        NetworkStream netstream = null;
        Status = string.Empty;
             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;
        catch (Exception ex)

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.


  • 18th January, 2009: Initial post


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


About the Author

Amir Hesami
Software Developer (Senior)
Australia Australia
No Biography provided

You may also be interested in...


Comments and Discussions

Generalsocket Pin
Member 1323964230-Jun-17 6:20
memberMember 1323964230-Jun-17 6:20 
Questionthe files were not received Pin
Member 1306012124-May-17 2:35
memberMember 1306012124-May-17 2:35 
Questionnull refrence exception Pin
Member 1039285723-Mar-17 23:02
professionalMember 1039285723-Mar-17 23:02 
QuestionNULL Exception thrown Pin
Member 124954037-May-16 4:49
memberMember 124954037-May-16 4:49 
AnswerRe: NULL Exception thrown Pin
iadol9-Jul-16 18:27
memberiadol9-Jul-16 18:27 
QuestionFor debugging Pin
robertkjr3d20-Mar-16 14:19
memberrobertkjr3d20-Mar-16 14:19 
QuestionHow to ascertain the real filename? Pin
robertkjr3d20-Mar-16 14:10
memberrobertkjr3d20-Mar-16 14:10 
AnswerRe: How to ascertain the real filename? Pin
robertkjr3d20-Mar-16 14:15
memberrobertkjr3d20-Mar-16 14:15 
GeneralRe: How to ascertain the real filename? Pin
Garth J Lancaster20-Mar-16 15:12
professionalGarth J Lancaster20-Mar-16 15:12 
Questionsave dialog box is not showing up Pin
Member 1208498625-Oct-15 1:21
memberMember 1208498625-Oct-15 1:21 
QuestionI got a memory disruption! Pin
Member 1205868814-Oct-15 9:02
memberMember 1205868814-Oct-15 9:02 
GeneralMy vote of 5 Pin
Member 1178754823-Jun-15 15:43
memberMember 1178754823-Jun-15 15:43 
QuestionSave dialog was not open Pin
chengji1810-Nov-14 4:23
memberchengji1810-Nov-14 4:23 
AnswerRe: Save dialog was not open Pin
FilipRooms22-Jun-15 4:00
memberFilipRooms22-Jun-15 4:00 
GeneralRe: Save dialog was not open Pin
Member 1208498625-Oct-15 1:31
memberMember 1208498625-Oct-15 1:31 
QuestionDoes the code Works On Internet? Pin
Agent_Spock9-Jul-14 2:07
professionalAgent_Spock9-Jul-14 2:07 
QuestionAmir Hesami Pin
Member 1075099519-May-14 0:23
memberMember 1075099519-May-14 0:23 
QuestionQuestion - how to enhance usability Pin
מתן פיכמן4-Dec-13 10:19
memberמתן פיכמן4-Dec-13 10:19 
QuestionSending COntent of file using java Pin
Member 1015929323-Aug-13 3:37
memberMember 1015929323-Aug-13 3:37 
Questioncode Pin
krunal solanki10-Mar-13 20:52
memberkrunal solanki10-Mar-13 20:52 
AnswerRe: code Pin
SLDragon17-May-13 0:28
memberSLDragon17-May-13 0:28 
QuestionError implementing to Form App. Pin
Member 968804416-Dec-12 2:09
memberMember 968804416-Dec-12 2:09 
AnswerRe: Error implementing to Form App. Pin
SLDragon17-May-13 0:11
memberSLDragon17-May-13 0:11 
QuestionProject code not downloading Pin
Member 327776012-Jul-12 5:04
memberMember 327776012-Jul-12 5:04 
AnswerRe: Project code not downloading Pin
Amir Hesami12-Jul-12 13:02
memberAmir Hesami12-Jul-12 13:02 
GeneralRe: Project code not downloading Pin
Member 327776013-Jul-12 0:52
memberMember 327776013-Jul-12 0:52 
Generalcode has some error Pin
Anurag Pradeep Gupta6-Apr-12 1:38
memberAnurag Pradeep Gupta6-Apr-12 1:38 
QuestionQuestion Pin
thepowercoder17-Nov-11 3:25
memberthepowercoder17-Nov-11 3:25 
Questionsalam Pin
arastoooo5-Sep-11 14:15
memberarastoooo5-Sep-11 14:15 
GeneralThank you! Pin
Poolee4-Sep-11 9:02
memberPoolee4-Sep-11 9:02 
GeneralError Occuring Pin
Member 792362814-May-11 14:00
memberMember 792362814-May-11 14:00 
GeneralRe: Error Occuring Pin
Dhirendra Jain14-Jun-11 12:05
memberDhirendra Jain14-Jun-11 12:05 
GeneralMy vote of 2 Pin
vsoft10-Oct-10 23:53
membervsoft10-Oct-10 23:53 
GeneralI got bug! Pin
hara2103-Mar-10 8:31
memberhara2103-Mar-10 8:31 
GeneralRe: I got bug! Pin
chengji1810-Nov-14 4:12
memberchengji1810-Nov-14 4:12 
GeneralRe: I got bug! Pin
chengji1810-Nov-14 5:46
memberchengji1810-Nov-14 5:46 
QuestionWould this work with &lt;4GB? Pin
RogueTrooper3-Jul-09 16:52
memberRogueTrooper3-Jul-09 16:52 
General[Message Deleted] Pin
it.ragester2-Apr-09 23:00
memberit.ragester2-Apr-09 23:00 
GeneralThreadAbortException Pin
Br1ll1@nce20-Jan-09 21:36
memberBr1ll1@nce20-Jan-09 21:36 
GeneralRe: ThreadAbortException Pin
Amir Hesami26-Jan-09 16:14
memberAmir Hesami26-Jan-09 16:14 
GeneralRe: ThreadAbortException Pin
Br1ll1@nce26-Jan-09 19:49
memberBr1ll1@nce26-Jan-09 19:49 
Generalfix need Pin
alex.shadowz20-Jan-09 3:38
memberalex.shadowz20-Jan-09 3:38 
GeneralRe: fix need Pin
Amir Hesami26-Jan-09 16:13
memberAmir Hesami26-Jan-09 16:13 
GeneralMy vote of 1 Pin
Chiew Heng Wah19-Jan-09 19:49
memberChiew Heng Wah19-Jan-09 19:49 
GeneralSuggestion Pin
Adrian Cole18-Jan-09 19:01
memberAdrian Cole18-Jan-09 19:01 
GeneralRe: Suggestion Pin
Br1ll1@nce20-Jan-09 21:53
memberBr1ll1@nce20-Jan-09 21:53 
AnswerRe: Suggestion Pin
Adrian Cole21-Jan-09 9:00
memberAdrian Cole21-Jan-09 9:00 
QuestionWhat about wcf? Pin
GSerjo18-Jan-09 6:22
memberGSerjo18-Jan-09 6:22 
Generalnice Pin
bysoulful18-Jan-09 4:52
memberbysoulful18-Jan-09 4:52 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 18 Jan 2009
Article Copyright 2009 by Amir Hesami
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid