How to use sockets to upload a . txt file to the server and on the server receive that file and save it to the directory?

Asked

Viewed 16 times

0

I’m three days trying to understand how this works and looking for examples, it turns out that most teach how to send text messages or chats between server and client, besides I’m not using windows Forms and all the examples I found was with windows Forms...

I can establish the connection between the client and the server but I can’t transfer the text file or the server can’t receive it... it turns out that the program doesn’t make any exceptions, as if everything happened as expected, but it doesn’t create the file. txt.

This is my client who sends the . txt file:

public void Client()
    {
        try
        {
            ipHost = Dns.GetHostEntry(dns);
            ipAddr = ipHost.AddressList[0];
            ipEndPoint = new IPEndPoint(ipAddr, 2500);

            // Create a TCP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);    
            try
            {
                string fileName = caminho + "wrt.txt";

                Console.WriteLine("Sending {0} to the host.", fileName);

                //O código abaixo são informações necessárias para salvar o arquivo recebido
                byte[] nomeArquivoByte = Encoding.ASCII.GetBytes(fileName);
                byte[] tamanhoDoNomeDoArquivo = BitConverter.GetBytes(nomeArquivoByte.Length);
                byte[] dadosDoArquivo = File.ReadAllBytes(fileName);
                byte[] clientDados = new byte[4 + nomeArquivoByte.Length + dadosDoArquivo.Length];

                tamanhoDoNomeDoArquivo.CopyTo(clientDados, 0);
                nomeArquivoByte.CopyTo(clientDados, 4);
                dadosDoArquivo.CopyTo(clientDados, 4 + nomeArquivoByte.Length);

                client.Connect(ipEndPoint);
                client.Send(clientDados);

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                Console.WriteLine("Enviado com sucesso.");

            } catch (Exception e) {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

And this the server, who receives the file and saves in my directory:

        private void Servidor()
    {
        try
        {
            ip = IPAddress.Parse(ipEnd);
            tcpListener = new TcpListener(ip, int.Parse(porta));
            tcpListener.Start();

            Console.WriteLine("Server iniciado");

            Socket client = tcpListener.AcceptSocket();

            client.ReceiveBufferSize = 16384; //tamanho do buffer 16kb

            Console.WriteLine("Recebendo arquivo");

            byte[] dados = new byte[1024*5000]; //tamanho máximo de 50mb para armazenar o arquivo
            int tamanhoBytesRecebidos = client.Receive(dados); //verificando tamanho do arquivo
            int tamanhoNomeArquivo = BitConverter.ToInt32(dados, 0); //tamanho do nome do arquivo
            string nomeArquivo = Encoding.ASCII.GetString(dados, 4, tamanhoNomeArquivo);

            BinaryWriter bWriter = new BinaryWriter(File.Open(caminhoRecepcaoArquivos + nomeArquivo, FileMode.Create));
            bWriter.Write(dados, 4 + tamanhoNomeArquivo, tamanhoBytesRecebidos - 4 - tamanhoNomeArquivo);//grava o arquivo recebido

            bWriter.Close();
            client.Close();
            Console.WriteLine("Recebido com sucesso!");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Erro: " + ex.Message);
        }
    }

It turns out that the code follows normally without launching any exceptions, so I don’t know why I can’t get the filed, or so why do I get it and it doesn’t save in the directory? If anyone can help me, or has another way to implement it, it would be of great help.

@Edit: I talked to a friend and solved the problem with this line:

byte[] nomeArquivoByte = Encoding.ASCII.GetBytes(Path.GetFileName(fileName));

I was passing not only the file but the complete folder, so I could not pass the file.

Credits to @Darkskeleton

  • of a look at the examples of socket send and socker receive

  • I had already seen the two links, I searched the entire net and I couldn’t find anything that would help me to send a simple text file...

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.