0

我正在尝试通过多播发送很长的内容。连接应该可以工作,因为可以发送一个字符串。

这是我的服务器端代码:

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);

这是在客户端(接收方):

byte[] buf = new byte[256];
serverIpPacket = new DatagramPacket(buf, buf.length);
System.out.println("waiting to receive");
multicastSocket.receive(serverIpPacket);
receivedIp = serverIpPacket.getAddress().getHostAddress();
currentServerStatusId = ByteBuffer.allocate(8).put(serverIpPacket.getData()).getLong();
//new String(serverIpPacket.getData(), 0, serverIpPacket.getLength());
System.out.println("received current ServerStatusId: " + currentServerStatusId);

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

4

1 回答 1

0

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

我必须把它放在客户端:

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

就这样

于 2012-10-22T18:19:42.050 回答