Project scenario:
UDP communication
Problem Description
提示:UDP 接收方收到的数据等于缓冲区长度,且远大于发送方发送的数据。
错误代码如下:
public void receivePackage() {
while(true) {
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
try {
socket.receive(packet);
byte[] data = packet.getData();
String s = new String(data, 0, data.length);
Log.d(TAG, "receivePackage: " + s);
if(s.equals("BYE")) break;
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
Cause Analysis:
In fact, when creating a string, the length of the data packet is set incorrectly, and the length should not use data.length
byte[] data = packet.getData();
String s = new String(data, 0, data.length);
solution:
Use packet.getLength() instead to solve
public void receivePackage() {
while(true) {
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
try {
socket.receive(packet);
byte[] data = packet.getData();
String s = new String(data, 0, packet.getLength());
Log.d(TAG, "receivePackage: " + s);
if(s.equals("BYE")) break;
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}