简体   繁体   中英

Sending double from matlab to java via UDP-packets

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM