So I got this simple udp client/server code from the internet, and it works. However, when I enter something that is shorter than the thing I entered before it, I get the remaining characters left over. For example, if I first enter:
kitty
And then enter:
cat
The second print reads as:
catty
I've been looking at other people with similar problems and most of them seem to be solved by clearing the byte array. However, if I try to implement their answers, it doesn't fix my problem. What do I need to do, and (maybe more importantly) where in the code should it go? Here is the code:
Client:
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);
}
}
}
You don't need to clear the byte array, but you do need to take some notice of the length of the DatagramPacket after the receive, via the getLength()
method; for example:
new String(packet.getData(), packet.getOffset(), packet.getLength());
You're doing that correctly in the server, but not in the client.
You also need to reset the length before calling receive()
. Otherwise the DatagramPacket
will keep shrinking to the length of the smallest packet received so far.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With