I'm trying to send doubles from Matlab(Simulink) to java. This is my code:
public static void main(String[] args) throws SocketException, UnknownHostException, IOException {
DatagramSocket socket = new DatagramSocket(25000);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true) {
socket.receive(packet);
String msg = new String(buf, 0, packet.getLength());
Double x = ByteBuffer.wrap(buf).getDouble();
System.out.println(x);
packet.setLength(buf.length);
}
}
I'm getting values but they really don't make sense...
Most likely you are sending double
s as little-endian but ByteBuffer assumes "network order" which is big-endian.
try
DatagramSocket socket = new DatagramSocket(25000);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
DoubleBuffer db = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
while (true) {
socket.receive(packet);
db.limit(packet.getLength() / Double.BYTES);
double x = db.get(0);
System.out.println(x);
}
Note: UCP is lossy, so some packets will be lost.