none
Send multiple files - Socket RRS feed

  • Question

  • Guys, I've been researching this a lot, but to no avail. We are developing a Client / Server application, where Client sends files to the Server. For sending 1 file it works perfectly, but the business need is for it to send all the files in the folder one by one. Does anyone have any idea how to do this? The following is the Client / Server code. (Remembering it's in Windows Forms, VS 2017).


    **Server Side**

                try
                {
                    string strEnderecoIP = "localhost";
                    ipEnd_servidor = new IPEndPoint(IPAddress.Parse(strEnderecoIP), 1234);
                    sock_Servidor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                    sock_Servidor.Bind(ipEnd_servidor);
                }
                catch (Exception ex)
                {
                    mensagemServidor = "Error : " + ex.Message;
                    return;
                }

                try
                {
                    sock_Servidor.Listen(100);
                    mensagemServidor = "Servidor em atendimento e aguardando para receber arquivo...";
                    Socket clienteSock = sock_Servidor.Accept();
                    clienteSock.ReceiveBufferSize = 16384;

                    byte[] dadosCliente = new byte[1024 * 500000];

                    int tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, 0);
                    int tamnhoNomeArquivo = BitConverter.ToInt32(dadosCliente, 0);
                    string nomeArquivo = Encoding.UTF8.GetString(dadosCliente, 4, tamnhoNomeArquivo);

                    BinaryWriter bWrite = new BinaryWriter(File.Open(caminhoRecepcaoArquivos + nomeArquivo, FileMode.Append));
                    bWrite.Write(dadosCliente, 4 + tamnhoNomeArquivo, tamanhoBytesRecebidos - 4 - tamnhoNomeArquivo);

                    while (tamanhoBytesRecebidos > 0)
                    {
                        tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, 0);
                        if (tamanhoBytesRecebidos == 0)
                        {
                            bWrite.Close();
                        }
                        else
                        {
                            bWrite.Write(dadosCliente, 0, tamanhoBytesRecebidos);
                        }
                    }
                    bWrite.Close();

                    clienteSock.Close();
                    mensagemServidor = "File received [" + nomeArquivo + "] (" + (tamanhoBytesRecebidos - 4 - tamnhoNomeArquivo) + " bytes recebido); Server Stopped";
                }
                catch (SocketException ex)
                {
                    mensagemServidor = ex.Message + " - Erro ao receber arquivo.";
                }
            } 


    **Client Side - Call the method to send the files**

            public void Send()
            {
                var dirInfo = new DirectoryInfo(@"C:\Diretorio\");
                var cliente = new FTCliente();
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    var mensagem = cliente.SendFiles(file.FullName);
                    lstMensagens.Items.Add(mensagem);
                }
             }


    **Method to send the files**
            
            public string SendFiles(string fileName)
            {
                var mensagemCliente = string.Empty;
                try
                {
                    string strEnderecoIP = "localhost";
                    IPEndPoint ipEnd_cliente = new IPEndPoint(IPAddress.Parse(strEnderecoIP), 1234);
                    Socket clientSock_cliente = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                    string filePath = "";
                    fileName = fileName.Replace("\\", "/");

                     while (fileName.IndexOf("/") > -1)
                    {
                        filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
                        fileName = fileName.Substring(fileName.IndexOf("/") + 1);
                    }

                    byte[] nomeArquivoByte = Encoding.UTF8.GetBytes(fileName);
                    if (nomeArquivoByte.Length > 5000 * 1024)
                        mensagemCliente += "File [ " + fileName + "] with incorrect size! </ br>";

                    if (fileName.Length < 52)
                        mensagemCliente += "File [" + fileName + "] Não tem o comprimento correto </ br>";

                    if (fileName.Any())
                    {
                         -- Validações internas
                    }

                    string path = filePath + fileName;

                    byte[] fileData = File.ReadAllBytes(path);
                    byte[] clientData = new byte[4 + nomeArquivoByte.Length + fileData.Length];
                    byte[] nomeArquivoLen = BitConverter.GetBytes(nomeArquivoByte.Length);

                    nomeArquivoLen.CopyTo(clientData, 0);
                    nomeArquivoByte.CopyTo(clientData, 4);
                    fileData.CopyTo(clientData, 4 + nomeArquivoByte.Length);

                    clientSock_cliente.Connect(ipEnd_cliente);
                    clientSock_cliente.Send(clientData, 0, clientData.Length, 0);
                    clientSock_cliente.Close();
                    mensagemCliente = "File [" + path + "] transferred.";
                }
                catch (Exception ex)
                {
                    mensagemCliente = ex.Message + " " + "\n Fail, server failed....";
                }
                return mensagemCliente;
            }
        }


    Thanks!
    Thursday, December 14, 2017 6:43 PM

Answers

  • Hello Aretha,

    I create a simple example base on your code. I separate the each file transferred into two parts. One is sending file name and another is sending file content.

    The server side.

     IPEndPoint ipEnd_servidor;
                Socket sock_Servidor;
                string fileName=string.Empty;
                try
                {
                    string strEnderecoIP = "xx.xxx.xxx.xx";
    
                    ipEnd_servidor = new IPEndPoint(IPAddress.Parse(strEnderecoIP), 1234);
                    sock_Servidor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    
                    sock_Servidor.Bind(ipEnd_servidor);
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error : " + ex.Message);
                    return;
                }
                while (true)
                {
                    try
                    {
                        sock_Servidor.Listen(100);
    
                        string mensagemServidor = "Servidor em atendimento e aguardando para receber arquivo...";
    
                        //serverside
                        Socket clienteSock = sock_Servidor.Accept();
    
                        byte[] notifyArray = new byte[1000];
    
                        clienteSock.Receive(notifyArray);
    
                        string notifyStr = Encoding.ASCII.GetString(notifyArray);
    
                        string temp = ipEnd_servidor.Address + ":" + ipEnd_servidor.Port + ".The File Name is ";
    
                        if (notifyStr.StartsWith(temp))
                        {
                            fileName = notifyStr.Substring(notifyStr.LastIndexOf('\\')).Replace("\0", "").Replace("\\","");
                            File.Create(fileName).Close();
                            clienteSock.Send(Encoding.ASCII.GetBytes("OK"));
                        }
    
                        byte[] dadosCliente = new byte[1024];
    
                        int tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, SocketFlags.None);
    
                        BinaryWriter bWrite = new BinaryWriter(File.Open(fileName, FileMode.Append));
    
                        bWrite.Write(dadosCliente);
    
                        while (tamanhoBytesRecebidos > 0)
                        {
                            tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, 0);
    
                            if (tamanhoBytesRecebidos == 0)
                            {
                                bWrite.Close();
                            }
                            else
                            {
                                bWrite.Write(dadosCliente, 0, tamanhoBytesRecebidos);
                            }
                        }
                        bWrite.Close();
    
                        clienteSock.Close();
    
                        Console.WriteLine("The serverside has received File  [" + fileName + "]......");
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message + " - Erro ao receber arquivo.");
                    }
                }
            }
     

    The client side

     public void Send()
            {
                var dirInfo = new DirectoryInfo(@"D:\Test2\doc");
                var cliente = new Program();
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    var mensagem = cliente.SendFiles(file.FullName);
                    Console.WriteLine(mensagem);
                }
            }
    
            public string SendFiles(string fileName)
            {
                var mensagemCliente = string.Empty;
    
                try
                {
                    string strEnderecoIP = "xx.xxx.xxx.xx";
                    IPEndPoint ipEnd_cliente = new IPEndPoint(IPAddress.Parse(strEnderecoIP),1234);
                    Socket clientSock_cliente = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
           
                    byte[] nomeArquivoByte = Encoding.UTF8.GetBytes(fileName);
    
                    byte[] fileData = File.ReadAllBytes(fileName);
    
                    clientSock_cliente.Connect(ipEnd_cliente);
    
                    string notifyString = "xx.xxx.xxx.xx:1234.The File Name is "+fileName;
                    byte[] notifyData = Encoding.ASCII.GetBytes(notifyString);
    
                    clientSock_cliente.Send(notifyData, 0, notifyData.Length, 0);
    
                    //Clientside
                    byte[] response= new byte[500];
                    clientSock_cliente.Receive(response);
                    string str = Encoding.ASCII.GetString(response);
                    if (str.Contains("OK")) {
                        clientSock_cliente.Send(fileData, 0, fileData.Length, 0);
    
                        clientSock_cliente.Close();
    
                        mensagemCliente = "File [" + fileName + "] transferred.";
                    }                           
                }
                catch (Exception ex)
                {
                    mensagemCliente = ex.Message + " " + "\n Fail, server failed....";
                }
                return mensagemCliente;
            }

    Result

    And I suggest that when you send multifile you need to compressed file. The profit of this approach is the server side will get one request and the file size is more smaller than before. As for how to compress and extract files, see here.

    Best regards,

    Neil Hu


    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.

    Friday, December 15, 2017 8:25 AM
    Moderator
  • Hello Aretha,

    Did you try the above code? Is there any update or any other assistance I could provide ? And if you have any concerns, please do not hesitate to let us know.

    Best regards,

    Neil Hu


    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.

    • Marked as answer by Aretha Lemos Thursday, October 25, 2018 7:56 PM
    Sunday, December 24, 2017 9:02 AM
    Moderator

All replies

  • Hello Aretha,

    I create a simple example base on your code. I separate the each file transferred into two parts. One is sending file name and another is sending file content.

    The server side.

     IPEndPoint ipEnd_servidor;
                Socket sock_Servidor;
                string fileName=string.Empty;
                try
                {
                    string strEnderecoIP = "xx.xxx.xxx.xx";
    
                    ipEnd_servidor = new IPEndPoint(IPAddress.Parse(strEnderecoIP), 1234);
                    sock_Servidor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    
                    sock_Servidor.Bind(ipEnd_servidor);
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error : " + ex.Message);
                    return;
                }
                while (true)
                {
                    try
                    {
                        sock_Servidor.Listen(100);
    
                        string mensagemServidor = "Servidor em atendimento e aguardando para receber arquivo...";
    
                        //serverside
                        Socket clienteSock = sock_Servidor.Accept();
    
                        byte[] notifyArray = new byte[1000];
    
                        clienteSock.Receive(notifyArray);
    
                        string notifyStr = Encoding.ASCII.GetString(notifyArray);
    
                        string temp = ipEnd_servidor.Address + ":" + ipEnd_servidor.Port + ".The File Name is ";
    
                        if (notifyStr.StartsWith(temp))
                        {
                            fileName = notifyStr.Substring(notifyStr.LastIndexOf('\\')).Replace("\0", "").Replace("\\","");
                            File.Create(fileName).Close();
                            clienteSock.Send(Encoding.ASCII.GetBytes("OK"));
                        }
    
                        byte[] dadosCliente = new byte[1024];
    
                        int tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, SocketFlags.None);
    
                        BinaryWriter bWrite = new BinaryWriter(File.Open(fileName, FileMode.Append));
    
                        bWrite.Write(dadosCliente);
    
                        while (tamanhoBytesRecebidos > 0)
                        {
                            tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, 0);
    
                            if (tamanhoBytesRecebidos == 0)
                            {
                                bWrite.Close();
                            }
                            else
                            {
                                bWrite.Write(dadosCliente, 0, tamanhoBytesRecebidos);
                            }
                        }
                        bWrite.Close();
    
                        clienteSock.Close();
    
                        Console.WriteLine("The serverside has received File  [" + fileName + "]......");
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message + " - Erro ao receber arquivo.");
                    }
                }
            }
     

    The client side

     public void Send()
            {
                var dirInfo = new DirectoryInfo(@"D:\Test2\doc");
                var cliente = new Program();
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    var mensagem = cliente.SendFiles(file.FullName);
                    Console.WriteLine(mensagem);
                }
            }
    
            public string SendFiles(string fileName)
            {
                var mensagemCliente = string.Empty;
    
                try
                {
                    string strEnderecoIP = "xx.xxx.xxx.xx";
                    IPEndPoint ipEnd_cliente = new IPEndPoint(IPAddress.Parse(strEnderecoIP),1234);
                    Socket clientSock_cliente = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
           
                    byte[] nomeArquivoByte = Encoding.UTF8.GetBytes(fileName);
    
                    byte[] fileData = File.ReadAllBytes(fileName);
    
                    clientSock_cliente.Connect(ipEnd_cliente);
    
                    string notifyString = "xx.xxx.xxx.xx:1234.The File Name is "+fileName;
                    byte[] notifyData = Encoding.ASCII.GetBytes(notifyString);
    
                    clientSock_cliente.Send(notifyData, 0, notifyData.Length, 0);
    
                    //Clientside
                    byte[] response= new byte[500];
                    clientSock_cliente.Receive(response);
                    string str = Encoding.ASCII.GetString(response);
                    if (str.Contains("OK")) {
                        clientSock_cliente.Send(fileData, 0, fileData.Length, 0);
    
                        clientSock_cliente.Close();
    
                        mensagemCliente = "File [" + fileName + "] transferred.";
                    }                           
                }
                catch (Exception ex)
                {
                    mensagemCliente = ex.Message + " " + "\n Fail, server failed....";
                }
                return mensagemCliente;
            }

    Result

    And I suggest that when you send multifile you need to compressed file. The profit of this approach is the server side will get one request and the file size is more smaller than before. As for how to compress and extract files, see here.

    Best regards,

    Neil Hu


    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.

    Friday, December 15, 2017 8:25 AM
    Moderator
  • Hello Aretha,

    Did you try the above code? Is there any update or any other assistance I could provide ? And if you have any concerns, please do not hesitate to let us know.

    Best regards,

    Neil Hu


    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.

    • Marked as answer by Aretha Lemos Thursday, October 25, 2018 7:56 PM
    Sunday, December 24, 2017 9:02 AM
    Moderator
  • Thank you so much for your solution, it works!

    Hello Aretha,

    Did you try the above code? Is there any update or any other assistance I could provide ? And if you have any concerns, please do not hesitate to let us know.

    Best regards,

    Neil Hu


    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.


    Thursday, October 25, 2018 7:57 PM
  • Thank you so much for your solution, it works!

    Hello Aretha,

    I create a simple example base on your code. I separate the each file transferred into two parts. One is sending file name and another is sending file content.

    The server side.

     IPEndPoint ipEnd_servidor;
                Socket sock_Servidor;
                string fileName=string.Empty;
                try
                {
                    string strEnderecoIP = "xx.xxx.xxx.xx";
    
                    ipEnd_servidor = new IPEndPoint(IPAddress.Parse(strEnderecoIP), 1234);
                    sock_Servidor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    
                    sock_Servidor.Bind(ipEnd_servidor);
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error : " + ex.Message);
                    return;
                }
                while (true)
                {
                    try
                    {
                        sock_Servidor.Listen(100);
    
                        string mensagemServidor = "Servidor em atendimento e aguardando para receber arquivo...";
    
                        //serverside
                        Socket clienteSock = sock_Servidor.Accept();
    
                        byte[] notifyArray = new byte[1000];
    
                        clienteSock.Receive(notifyArray);
    
                        string notifyStr = Encoding.ASCII.GetString(notifyArray);
    
                        string temp = ipEnd_servidor.Address + ":" + ipEnd_servidor.Port + ".The File Name is ";
    
                        if (notifyStr.StartsWith(temp))
                        {
                            fileName = notifyStr.Substring(notifyStr.LastIndexOf('\\')).Replace("\0", "").Replace("\\","");
                            File.Create(fileName).Close();
                            clienteSock.Send(Encoding.ASCII.GetBytes("OK"));
                        }
    
                        byte[] dadosCliente = new byte[1024];
    
                        int tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, SocketFlags.None);
    
                        BinaryWriter bWrite = new BinaryWriter(File.Open(fileName, FileMode.Append));
    
                        bWrite.Write(dadosCliente);
    
                        while (tamanhoBytesRecebidos > 0)
                        {
                            tamanhoBytesRecebidos = clienteSock.Receive(dadosCliente, dadosCliente.Length, 0);
    
                            if (tamanhoBytesRecebidos == 0)
                            {
                                bWrite.Close();
                            }
                            else
                            {
                                bWrite.Write(dadosCliente, 0, tamanhoBytesRecebidos);
                            }
                        }
                        bWrite.Close();
    
                        clienteSock.Close();
    
                        Console.WriteLine("The serverside has received File  [" + fileName + "]......");
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message + " - Erro ao receber arquivo.");
                    }
                }
            }
     

    The client side

     public void Send()
            {
                var dirInfo = new DirectoryInfo(@"D:\Test2\doc");
                var cliente = new Program();
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    var mensagem = cliente.SendFiles(file.FullName);
                    Console.WriteLine(mensagem);
                }
            }
    
            public string SendFiles(string fileName)
            {
                var mensagemCliente = string.Empty;
    
                try
                {
                    string strEnderecoIP = "xx.xxx.xxx.xx";
                    IPEndPoint ipEnd_cliente = new IPEndPoint(IPAddress.Parse(strEnderecoIP),1234);
                    Socket clientSock_cliente = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
           
                    byte[] nomeArquivoByte = Encoding.UTF8.GetBytes(fileName);
    
                    byte[] fileData = File.ReadAllBytes(fileName);
    
                    clientSock_cliente.Connect(ipEnd_cliente);
    
                    string notifyString = "xx.xxx.xxx.xx:1234.The File Name is "+fileName;
                    byte[] notifyData = Encoding.ASCII.GetBytes(notifyString);
    
                    clientSock_cliente.Send(notifyData, 0, notifyData.Length, 0);
    
                    //Clientside
                    byte[] response= new byte[500];
                    clientSock_cliente.Receive(response);
                    string str = Encoding.ASCII.GetString(response);
                    if (str.Contains("OK")) {
                        clientSock_cliente.Send(fileData, 0, fileData.Length, 0);
    
                        clientSock_cliente.Close();
    
                        mensagemCliente = "File [" + fileName + "] transferred.";
                    }                           
                }
                catch (Exception ex)
                {
                    mensagemCliente = ex.Message + " " + "\n Fail, server failed....";
                }
                return mensagemCliente;
            }

    Result

    And I suggest that when you send multifile you need to compressed file. The profit of this approach is the server side will get one request and the file size is more smaller than before. As for how to compress and extract files, see here.

    Best regards,

    Neil Hu


    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.


    Thursday, October 25, 2018 7:58 PM