how to send file by .net 5 tcpclient

钢 屈 371 Reputation points
2021-09-06T02:50:24.427+00:00

I code xamarin.forms project.
I have view the page(https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=net-5.0).
The example is send message by tcpclient.
I don't know how to read a file and send file by tcpclient.
Can you please give me a example?
Thank you.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-09-07T06:25:37.083+00:00

    This is another simple example of using TCP, I hope it can provide you with some ideas.

    Server:

            static void Main(string[] args)  
            {  
                ReceiveTCP(8088);  
            }  
            private const int BufferSize = 1024;  
            public static void ReceiveTCP(int port)  
            {  
                TcpListener Listener = null;  
                try  
                {  
                    Listener = new TcpListener(IPAddress.Any, port);  
                    Listener.Start();  
                }  
                catch (Exception ex)  
                {  
                    Console.WriteLine(ex.Message);  
                }  
                byte[] RecData = new byte[BufferSize];  
                int RecBytes;  
                for (; ; )  
                {  
                    TcpClient client = null;  
                    NetworkStream netstream = null;  
                    try  
                    {  
                        client = Listener.AcceptTcpClient();  
                        netstream = client.GetStream();  
                        Console.WriteLine("Connected to a client...");  
      
                        string SaveFileName = @"C:\xxx\2.docx";  
      
                        int totalrecbytes = 0;  
                        using (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)  
                    {  
                        Console.WriteLine(ex.Message);  
                    }  
                    finally   
                    {  
                        netstream.Close();  
                        client.Close();  
                    }  
                }  
            }  
    

    Client:

           private const int BufferSize = 1024;  
            static void Main(string[] args)  
            {  
                SendTCP(@"d:\xxx\test.docx", "localhost", 8088);  
            }  
            public static void SendTCP(string fileName, string ip, Int32 port)  
            {  
                byte[] SendingBuffer = null;  
                TcpClient client = null;  
                NetworkStream netstream = null;  
                try  
                {  
                    client = new TcpClient(ip, port);  
                    Console.WriteLine("Connected to the Server...");  
                    netstream = client.GetStream();  
                    FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);  
                    int NoOfPackets = Convert.ToInt32  
                   (Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(BufferSize)));  
                    int TotalLength = (int)Fs.Length, CurrentPacketLength;  
                    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);  
                    }  
                    Console.WriteLine("Sent " + Fs.Length.ToString() + "bytes to the server");  
                    Fs.Close();  
                }  
                catch (Exception ex)  
                {  
                    Console.WriteLine(ex.Message);  
                }  
                finally  
                {  
                    netstream.Close();  
                    client.Close();  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2021-09-07T01:35:25.367+00:00

    Do you need to use TcpClient/Sockets specifically? If not you can just use HttpClient - here's a pretty good tutorial demonstrates it:
    https://www.youtube.com/watch?v=KPDGtLeNClQ

    Example client:
    https://github.com/jfversluis/XFUploadFile/blob/main/XFUploadFile/MainPage.xaml.cs#L30

    Example server:
    https://github.com/jfversluis/XFUploadFile/blob/main/XFUploadFile.Server/Controllers/UploadFileController.cs#L36

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.