title: Transfer a file through UDP in java
body: <p>I have the following algorithm implemented in Java which uses TCP/IP:</p>
  <pre><code>-Client request a file
  -Server checks if the file exists
    - if do: send contents of the file to the client
    - if not: send &quot;file not found&quot; msg to the client
  </code></pre>
  <p>Now I`m having trouble implementing that using UDP Datapackets.  Here is my code:</p>
  <hr />
  <h3>CLIENT:</h3>
  <pre><code>package br.com.redes.client;
  
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.PrintWriter;
  import java.net.Socket;
  import java.net.UnknownHostException;
  
  import br.com.redes.configuration.CommonKeys;
  
  public class TCPClient {
      public static void exibirCabecalho(){
          System.out.println(&quot;-------------------------&quot;);
          System.out.println(&quot;TCP CLIENT&quot;);
          System.out.println(&quot;-------------------------&quot;);
      }
      
      public static void main(String[] args) throws IOException {
  
          TCPClient.exibirCabecalho();
          
          Socket echoSocket = null;
          PrintWriter out = null;
          BufferedReader in = null;
  
          if (args.length != 1){
              System.out.println(&quot;O Programa deve ser chamado pelo nome + nome do servidor&quot;);
              System.out.println(&quot;Ex: java TCPClient localhost&quot;);
              System.exit(1);
          }
          
          System.out.println(&quot;Conectando ao servidor...&quot;);
          try {
              echoSocket = new Socket( args[0] , CommonKeys.PORTA_SERVIDOR);
              out = new PrintWriter(echoSocket.getOutputStream(), true);
              in = new BufferedReader(new InputStreamReader(echoSocket
                      .getInputStream()));
          } catch (UnknownHostException e) {
              System.err.println(&quot;Host não encontrado (&quot; + args[0] + &quot;)&quot;);
              System.exit(1);
          } catch (IOException e) {
              System.err.println(&quot;Erro ao inicializar I/O para conexao&quot;);
              System.exit(1);
          }
  
          System.out.println(&quot;Conectado, digite 'sair' sem as aspas para finalizar&quot;);
          
          BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
          String userInput;
  
          while ((userInput = stdIn.readLine()) != null) {
              out.println(userInput);
              String inputLine = in.readLine(); 
              
              if (inputLine == null){
                  System.out.println(&quot;Servidor terminou a conexão.&quot;);
                  System.out.println(&quot;Saindo...&quot;);
                  break;
              }
              
              System.out.println(&quot;Servidor: &quot; + inputLine.replace(&quot;\\n&quot;, &quot;\n&quot;));
          }
  
          out.close();
          in.close();
          stdIn.close();
          echoSocket.close();
      }
  
  }
  </code></pre>
  <hr />
  <h3>SERVER:</h3>
  <pre><code>package br.com.redes.server;
  
  import java.io.BufferedReader;
  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.FileReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.PrintWriter;
  import java.net.ServerSocket;
  import java.net.Socket;
  
  import br.com.redes.configuration.CommonKeys;
  
  public class TCPServer {
      public static void exibirCabecalho(){
          System.out.println(&quot;-------------------------&quot;);
          System.out.println(&quot;TCP SERVER&quot;);
          System.out.println(&quot;-------------------------&quot;);
      }
      
      public static void main(String[] args) throws IOException {
  
          TCPServer.exibirCabecalho();
          ServerSocket serverSocket = null;
          try {
              serverSocket = new ServerSocket( CommonKeys.PORTA_SERVIDOR );
          } catch (IOException e) {
              System.err.println(&quot;Erro ao iniciar servidor na porta: &quot; + CommonKeys.PORTA_SERVIDOR );
              System.exit(1);
          }
  
          System.out.println(&quot;Iniciando servidor na porta: &quot; + CommonKeys.PORTA_SERVIDOR);
          System.out.println(&quot;Aguardando cliente...&quot;);
          Socket clientSocket = null;
          try {
              clientSocket = serverSocket.accept();
          } catch (IOException e) {
              System.err.println(&quot;Erro ao receber conexoes.&quot;);
              System.exit(1);
          }
  
          PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
          BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
          
          String inputLine, outputLine;
  
          System.out.println(&quot;Cliente conectado, aguardando caminhos pra leitura...&quot;);
          while ((inputLine = in.readLine()) != null) {
              
              if (inputLine.equalsIgnoreCase(&quot;sair&quot;)) {
                  System.out.println(&quot;Sair detectado, fechando servidor...&quot;);
                  break;
              }
              
              outputLine = processar(inputLine);
               out.println(outputLine);
          }
          out.close();
          in.close();
          clientSocket.close();
          serverSocket.close();
      }
  
      private static String processar(String inputLine) {
          final String ARQUIVO_NAO_ENCONTRADO = &quot;arquivo não encontrado.&quot;;
          final String ARQUIVO_IO = &quot;erro ao ler arquivo.&quot;;
          
          System.out.println(&quot;Procurando arquivo: &quot; + inputLine);
          File f = new File(inputLine);
          try {
              BufferedReader input =  new BufferedReader(new FileReader(f));
              String linha = null;
              StringBuffer retorno = new StringBuffer();
              
              retorno.append(&quot;\\n&quot;);
              retorno.append(&quot;Arquivo encontrado, lendo conteudo: &quot; + inputLine + &quot;\\n&quot;);
              while (( linha = input.readLine()) != null){
                    retorno.append(linha  + &quot;\\n&quot;);
              }
              retorno.append(&quot;fim da leitura do arquivo\\n&quot;);
              return retorno.toString();
          } catch (FileNotFoundException e) {
              return ARQUIVO_NAO_ENCONTRADO;
          } catch (IOException e) {
              return ARQUIVO_IO;
          }
      }
  }
  </code></pre>