Java 通过UDP多播发送长消息

Java 通过UDP多播发送长消息,java,udp,multicast,lan,bufferunderflowexception,Java,Udp,Multicast,Lan,Bufferunderflowexception,我正在尝试通过多播发送长消息。 连接应该可以工作,因为可以发送字符串 这是我的服务器端代码: currentServerStatusId = Server.getServerStatusVersionId(); buf = ByteBuffer.allocate(8).putLong(currentServerStatusId).array(); //long should be 8 bytes in Java InetAddress group = InetAddress.getByName(

我正在尝试通过多播发送长消息。 连接应该可以工作,因为可以发送字符串

这是我的服务器端代码:

currentServerStatusId = Server.getServerStatusVersionId();
buf = ByteBuffer.allocate(8).putLong(currentServerStatusId).array(); //long should be 8 bytes in Java
InetAddress group = InetAddress.getByName(multicastAddress);
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
socket.send(packet);
这是在客户端(接收方):

这给了我一个BufferUnderflowException。 显然,当我在接收方/客户端的allocate方法中将大小从8加倍到16时,它确实起作用。
但是它返回0而不是我的测试值(类似于68763)

好的,对不起,麻烦了,但我自己刚刚找到了答案:

我必须把这个放在客户端:

ByteBuffer buffer = ByteBuffer.wrap(serverIpPacket.getData());
currentServerStatusId = buffer.getLong();

仅此而已

您会发现使用DataInputStream和DataOutputStream更简单,效率更高。
ByteBuffer buffer = ByteBuffer.wrap(serverIpPacket.getData());
currentServerStatusId = buffer.getLong();