I'm trying to send a long over a multicast. The connection should work, because it's possible to send a String.

This is my serverside code:

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

and this is on the client side (the receiver):

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

This gives me a BufferUnderflowException. Apparently it does work when I double the size from 8 to 16 in the allocate method on the receiver/client side. But then it returns 0 instead of my testing value (something like 68763)

有帮助吗?

解决方案

Okay, sorry, for the trouble but I just found the answer myself:

I have to put this in the client side:

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

that's all

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top