问题
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:
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);
回答1:
socket.receive(packet);
byte[] data = new byte[packet.getLength()];
System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());
回答2:
DatagramPacket.getLength()
returns the actual length of the received packet. Unless you created the packet with a non-zero offet, that means the data is at {0..getLength()-1}
.
Note that this means the original length you created the DatagramPacket
with is lost, which in turn implies that you must either use a new DatagramPacket
per receive, or at least re-initalize its data buffer via setData()
. Otherwise the DatagramPacket
will keep shrinking to the size of the smallest packet received.
回答3:
You have to check packet.getOffset()
to find where in the buffer the received data starts and packet.getLength()
to get the length of the data (in number of bytes).
You should also consider that if the received packet is too large to fit in the provided buffer (in your case >1024 bytes), the extra data is simply discarded. Unless you have to be very careful on memory usage, you should use a larger buffer to make sure that the entire packet will fit. In case of UDP, the maximum packet size is 64kB.
回答4:
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?
来源:https://stackoverflow.com/questions/8229064/how-to-get-rid-of-the-empty-remaining-of-the-buffer