Flush datagram buffer in Java

So, I got this simple udp client / server code from the internet and it works. However, when I entered something shorter than what I entered before it, I will leave the remaining characters. For example, if I first enter:

kitty 

And then enter:

 cat 

The second seal reads:

 catty 

I looked at other people with similar problems, and most of them seem to be solved by clearing the byte array. However, if I try to execute their answers, this will not fix my problem. What do I need to do, and (perhaps more importantly) where in the code should I go? Here is the code:

Customer:

 import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 20700); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } 

Server:

 import java.io.*; import java.net.*; import java.util.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(21200); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String( receivePacket.getData(), 0, receivePacket.getLength()); System.out.println("RECEIVED: " + sentence); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } 
+4
source share
1 answer

You do not need to clear the byte array, but you need to pay attention to the length of the DatagramPacket after receiving it through the getLength() method; eg:

 new String(packet.getData(), packet.getOffset(), packet.getLength()); 

You are doing this correctly on the server, but not on the client.

You also need to reset the length before receive() called. Otherwise, DatagramPacket will continue to shrink to the length of the smallest packet received so far.

+6
source

Source: https://habr.com/ru/post/1257400/


All Articles