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.
This is my code for sender:
while (fso.hasNextBlock()){
byte[] temp1 =fso.nextBlock();
int size1 = temp1.length;
packet=new DatagramPacket(temp1, size1,ipaddress,port);
socket.send(packet);
// Thread.sleep(100);
}
This is the receiver 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
}
Is anything wrong in my code?
I am not familiar with peer to peer networks. Which is better to use, TCP or UDP in file sharing networks?