udp Java datagramsocket接收到不完整的消息
我正在开发一个小程序,使用udp通过网络传输字符串命令。我发送的大多数字符串都被正确接收,尽管有一个特定的字符串没有被完全接收。我不知道问题出在发送端还是接收端。 正确接收的字符串示例:“connect 123.123.1.1” 未正确接收的字符串:“a/name/123.123.1.1”收到该字符串时得到的信息:“a/name/123” 发送代码:
public void sendToAll(String massage) {
//send massage to all clients
byte[] sendData = new byte[1500];
//clients is a linked list
for (int i = 0; i < clients.size(); i++) {
String ip = clients.get(i).ip;
sendData = massage.getBytes();
try {
InetAddress IPAddress = InetAddress.getByName(ip);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 11222);
clientSocket.send(sendPacket);
} catch (Exception e) {
}
}
}
接收代码:
byte[] receiveData = new byte[1500];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String massage = new String(receivePacket.getData());
//operations for other commands
if (massage.startsWith("a/")) {
String[] info = massage.split("/");
//operations for this command
}
}
# 1 楼答案
虽然我目前不知道问题的原因,但我在代码中找到了一些东西,也许其中一个与所有这些问题的原因有关。 首先,在send方法中,在将字符串命令编码为字节之前,分配一个大小为1500的sendData缓冲区。不需要它,因为方法getBytes()返回一个新的字节数组。然而,这真的不应该引起任何问题
更让我担心的是接收方法,还有那一行:
根据java api文档,数据包的getData()方法将返回传递给它的缓冲区。该缓冲区有1500字节长,如果试图以这种方式使用字符串构造函数,则会占用整个1500字节。可能应该是: