none
Need a Code for TCP Connection ! RRS feed

  • Question

  • Hello Experts,

    I have a txt file which adding data always now i need a C# code to transfer this file from a server (server.exe) to another computer (client.exe) & append new data in same file using TCP connection (IP address & Port).
    Process should be start using start button from server.exe and keep alive till user stop.

    Regards !!!


    Sunday, October 20, 2019 2:17 PM

All replies

  • In TCP, the side that initiates the connection is called the "client", and it reaches out to a "server".  There are many, many samples on the web of making a TCP connection in C#.  Note that the receiving side has to be listening in order to receive connections.

    How will the sending side know which computer to contact?  Will the two machines be inside the same network?


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Monday, October 21, 2019 6:09 AM
  • Client side exe will communicate to server using server IP & port (port that is already define by server side exe) & both machines inside the same network.

    Monday, October 21, 2019 6:30 AM
  • Hi Enhance Technology, 

    Thank you for posting here.

    For your question, you need C# code to transfer a file using TCP connection.

    I make a test on my side, and you can refer to the following code.

    Server:

        public partial class Form1 : Form
        {
            TcpListener listener;
            public Form1()
            {
                InitializeComponent();
            }
            private void BtnBegin_Click(object sender, EventArgs e)
            {
                btnBegin.Enabled = false;
                listener = new TcpListener(IPAddress.Parse("IP address"), 7890);
                listener.Start();
                ReceiveMsg();
            }
            public void ReceiveMsg()
            {
                while (true)
                {
                    try
                    {
                        int size = 0;
                        int len = 0;
                        TcpClient client = listener.AcceptTcpClient();
    
                        if (client.Connected)
                        {
                            listBox1.Items.Add("Client have connected to server");                  
                        }
                        NetworkStream stream = client.GetStream();
                        if (stream != null)
                        {
                            SaveFileDialog sfd = new SaveFileDialog();
                            if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                            {
                                string fileSavePath = sfd.FileName;
                                FileStream fs = new FileStream(fileSavePath, FileMode.Create, FileAccess.Write);
    
                                byte[] buffer = new byte[512];
                                while ((size = stream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    fs.Write(buffer, 0, size);
                                    len += size;
                                }
                                fs.Flush();
                                stream.Flush();
                                stream.Close();
                                client.Close();
                                listBox1.Items.Add("File have saved successfully");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Exception: {ex.Message}");
                    }
                }
            }
        }

    Client:

            private void Button1_Click(object sender, EventArgs e)
            {
                string path = @"D:\test.txt";
                TcpClient client = new TcpClient();
                client.Connect(IPAddress.Parse("IP address"), 7890);
                NetworkStream ns = client.GetStream();
                FileStream fs = new FileStream(path, FileMode.Open);
                int size = 0;   
                long len = 0; 
                while (len < fs.Length)
                {
                    byte[] buffer = new byte[512];
                    size = fs.Read(buffer, 0, buffer.Length);
                    ns.Write(buffer, 0, size);
                    len += size;   
                }
                fs.Flush();
                ns.Flush();
                fs.Close();
                ns.Close();
                MessageBox.Show("Send file successfully");
            }

    Result of my test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, October 21, 2019 6:59 AM
    Moderator
  • Thanks for your suggestion


    Some changes required actually i need to define client IP address & port from a txt file to communication and how to restrict starting of duplicate exe for end (only single server OR client exe should be run on a single machine) ? 


     


    Monday, October 21, 2019 7:54 AM
  • Hi Enhance Technology, 

    Thanks for your feedback.

    I have updated my client’s code, and you can check whether the content read from a text file is correct.

    Code:

                string path = @"the path of file which contains the content you want to send";
                string filePath = @"your path of text file";
                TcpClient client = new TcpClient();
                string[] infoArray = File.ReadAllLines(filePath);
                string ipAddress = infoArray[0];
                int port = Convert.ToInt32(infoArray[1]);
                if (ipAddress.Equals("your ipaddress") && port == 7890)
                {
                    client.Connect(IPAddress.Parse(ipAddress), port);
                    NetworkStream ns = client.GetStream();
                    FileStream fs = new FileStream(path, FileMode.Open);
                    int size = 0;
                    long len = 0;
                    while (len < fs.Length)
                    {
                        byte[] buffer = new byte[512];
                        size = fs.Read(buffer, 0, buffer.Length);
                        ns.Write(buffer, 0, size);
                        len += size;
                    }
                    fs.Flush();
                    ns.Flush();
                    fs.Close();
                    ns.Close();
                    MessageBox.Show("Send file successfully");
                }
                else
                {
                    MessageBox.Show("Error ipaddress or port");
                }
    

    Content in my text file:

    Result of the test if read the wrong ip address or port:

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, October 30, 2019 9:07 AM
    Moderator