title: Peer to peer file transfer in java
body: <p>I am trying to make a peer to peer file sharing network in Java. I am using UDP connection to send packets over the network. But I can't transfer a complete file though a UDP connection. Most of the  packets are missing  every time. If I send the packets with delay the receiver get all the packets.</p>
  
  <p>This is my code for sender:</p>
  
  <pre><code>while (fso.hasNextBlock()){   
     byte[] temp1 =fso.nextBlock();   
     int size1 = temp1.length;  
  
     packet=new DatagramPacket(temp1, size1,ipaddress,port);
     socket.send(packet);                           
  
     // Thread.sleep(100);
  } 
  </code></pre>
  
  <p>This is the receiver code:</p>
  
  <pre><code>FileOutputStream  out=new FileOutputStream(file);
  byte[] data=new byte[size];
  DatagramPacket packet=new DatagramPacket(data, data.length);
  int i=0;
  while(true){                   
      socket.receive(packet);
      out.write(packet.getData());
      System.out.println("packet "+i);
      i++;
      ..... // some codes                    
  }
  </code></pre>
  
  <p>Is anything wrong in my code?<br>
  I am not familiar with peer to peer networks. Which is better to use, TCP or UDP in file sharing networks?</p>