Search code examples
javaudpbufferpacketdatagram

When sending datagram packets, the data of the packet is duplicated. (java)


UDPclient:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    DatagramSocket socket;
    DatagramPacket packet;
    String str = "";
    byte[] buffer;
    String serverIP = "192.168.0.16";
    int serverPORT = 10789;
    Scanner sc = new Scanner(System.in);

    try {
        socket = new DatagramSocket();
        while(true) {
            System.out.print("To server : ");
            str = sc.nextLine();
            if(str.equals("exit")) {
                System.out.println("exit");
                break;
            }
            buffer = str.getBytes();
            packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(serverIP), serverPORT);
            socket.send(packet);
            System.out.println("sent message : " + str);
        } 
        socket.close();
    } catch (skip)

UDPserver:

byte[] buffer = new byte[1024];

public static void main(String[] args){
    int port = 10789;
    DatagramSocket socket;
    DatagramPacket packet;
    byte[] buffer = new byte[1024];

    try {
        socket = new DatagramSocket(port);
        packet = new DatagramPacket(buffer, buffer.length);
        while(true){
            socket.receive(packet);
            String text = new String(packet.getData());
            if(text.equals("exit")){
                System.out.println("exit");
                break;
            }
            System.out.println("received : "+text);
        }
    }

When I put the input many times, The data of the packet is duplicated.

Example: While I was typing:

type abcdeg

displayed abcdeg at server

type qwe

displayed qwedeg at server

What is wrong? How to clean buffer?


Solution

  • In the server code the same buffer is reused for all the received packets (which is a good thing). However that means that data from previous packets is present in the buffer until it is overwritten. As you've seen, when you receive a packet that is shorter than the previous one, only the first bytes in the buffer are overwritten, up to the length of the received message.

    new String(packet.getData()) lets the String constructor figure out how long the data is by looking at the contents of the buffer. Instead, use another constructor that lets you specify the length of the data: new String(packet.getData(), 0, packet.getLength()).