UDP文件发送数据丢失

时间:2018-07-17 14:39:09

标签: java sockets udp

我有以下代码。我有大约500 KB的文本文件,并且以这种方式将其从客户端发送到服务器。文本文件中的每一行都包含64个字母,即64个字节。传输完成后,传输的文件约为150 kbs,而我的原始文件约为500 kbs。通过先转换为字节发送每一行是否可以接受?此外,传输文件中的行顺序也会发生变化。

客户

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();
}

服务器

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();
}

我知道udp中可能会有数据包丢失,但是3/2丢失了,所以我发现它太多了,不知道这是否是因为我的代码而不是udp的本质。 udp代码也比udp慢。是否存在这样的问题:“ TCP对于小型数据传输更快”?

0 个答案:

没有答案