我试图使用java UDP套接字从客户端向服务器发送一个int数组。我在客户端硬编码了4个数字的数组,我发送数字4(数组的长度),服务器接收它,然后从客户端发送数组。但是在服务器中,当我打印数组时,第一个数字被打印,然后是3个零。
client.java
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class clien {
public static void main(String args[]) throws Exception {
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("localhost");
byte[] sendData;
int number = 4;
sendData = ByteBuffer.allocate(4).putInt(number).array();
DatagramPacket sendPacket = new DatagramPacket(sendData, 4, ip, 1234);
datagramSocket.send(sendPacket);
int[] n = new int[4];
n[0] = 23;
n[1] = 44;
n[2] = 9;
n[3] = 12;
ByteBuffer byteBuffer = ByteBuffer.allocate(n.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(n);
sendData = byteBuffer.array();
sendPacket = new DatagramPacket(sendData, number, ip, 1234);
datagramSocket.send(sendPacket);
}
}
server.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class server {
public static void main(String args[]) throws Exception{
byte[] receivedData = new byte[1024];
DatagramSocket datagramSocket = new DatagramSocket(1234);
while (true) {
DatagramPacket datagramPacket = new DatagramPacket(receivedData, receivedData.length);
datagramSocket.receive(datagramPacket);
int numbers = ByteBuffer.wrap(receivedData).getInt();
datagramPacket = new DatagramPacket(receivedData, receivedData.length);
datagramSocket.receive(datagramPacket);
IntBuffer intBuffer = ByteBuffer.wrap(receivedData).asIntBuffer();
int[] n = new int[numbers];
intBuffer.get(n);
for (int i = 0; i < numbers; i++) {
System.out.println(n[i]);
}
}
}
}
在这种情况下,服务器打印的是: 23 0 0 0
..我无法弄清楚错误。
答案 0 :(得分:4)
您只发送缓冲区的前4个字节..
int number = 4;
sendPacket = new DatagramPacket(sendData, number, ip, 1234);
number为4,但需要乘以int的长度(4个字节)
sendPacket = new DatagramPacket(sendData, number*4, ip, 1234);
或者sendData最初以正确的长度构建..
sendPacket = new DatagramPacket(sendData, sendData.length, ip, 1234);
另外,请不要忘记UDP数据包可以按任何顺序到达,或者根本不能到达。因此,即使您发送长度数据包然后发送数据包,它们也可能无法按顺序到达甚至丢失。由于这些原因,UDP数据包中的数据应该独立于其他数据。
在您的情况下,您不需要发送数据包来指定第二个数据包中的数量。只需将接收的数据包长度除以4即可。