通过UDP数据包从matlab发送两倍到java

时间:2016-02-28 10:06:50

标签: java matlab udp simulink

我正在尝试将来自Matlab(Simulink)的双打发送到java。 这是我的代码:

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

我正在获得价值,但他们真的没有意义......

1 个答案:

答案 0 :(得分:4)

你最有可能发送double作为小端,但ByteBuffer假定“网络顺序”是big-endian。

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

注意:UCP是有损的,因此有些数据包会丢失。