Search code examples
javasocketsnetwork-programmingudpdatagram

How to get rid of the empty remaining of the buffer?


I have a server-client application that is using a datagram socket to exchange messages. I have initially set the buffer size to be 1024 bytes because I dont know the length of the messages. When I send something that is shorter than 1024 bytes I get the rest of my string displayed as some weird characters (null characters or I am not sure how they are called). Here is a screen: string buffer null characters

Client code: byte[] buf = ("This is another packet.\n").getBytes(); DatagramPacket packet = new DatagramPacket(buf, buf.length, inetAddress, serverport); socket.send(packet)

Server code: byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet);


Solution

  • Ok so I came up with a solution that worked for me:

        public String getRidOfAnnoyingChar(DatagramPacket packet){
            String result = new String(packet.getData());
            char[] annoyingchar = new char[1];
            char[] charresult = result.toCharArray();
            result = "";
            for(int i=0;i<charresult.length;i++){
                if(charresult[i]==annoyingchar[0]){
                    break;
                }
                result+=charresult[i];
            }
            return result;
        }
    

    EDIT: There exists a better solution using ByteArrayOutputStream which can be found here: How to reinitialize the buffer of a packet?