I have the following codes. I have text file having about 500 kilobytes and I am sending this from client to server this way. Each line in the text file containt 64 letters so 64 bytes. After transfer completed, transferred file is about 150 kbs while my original file is about 500 kbs. Is it okey to send each line by converting to byte first? Also, line order changes in transferred file.
Client
private static DatagramSocket socket;
private static InetAddress address;
private static byte[] buf = new byte[64];
static Scanner file;
public static void main(String[] args) throws IOException{
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
file = new Scanner(new File("sentfile.txt"));
DatagramPacket packet;
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
buf = line.getBytes();
packet = new DatagramPacket(buf, buf.length, address, 1100);
socket.send(packet);
}
}
file.close();
socket.close();
}
Server
private static DatagramSocket udpSocket;
private static byte[] buffer = new byte[64];
private static boolean running;
static PrintWriter writer;
public static void main(String[] args) throws IOException {
udpSocket = new DatagramSocket(1100);
running = true;
writer = new PrintWriter("receivedfile.txt");
DatagramPacket packet;
while(running) {
packet = new DatagramPacket(buffer, buffer.length);
udpSocket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buffer, buffer.length, address, port);
String received = new String(packet.getData(), 0, packet.getLength());
writer.write(received);
writer.write(System.getProperty("line.separator"));
if (received.equals("end")) {
running = false;
continue;
}
}
writer.close();
udpSocket.close();
}
I know there can be packet loss in udp but 3/2 is lost so I found it too much and wonder if it is because of my code not the nature of udp. Also udp code works slower than udp. Is there a such thing "TCP is faster for small sized data transfer"?