2016-02-28 59 views
3

我想從Matlab(Simulink)發送雙打到java。 這是我的代碼:通過UDP包發送雙從matlab到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); 
     } 
} 

我得到的值,但他們真的沒有任何意義......

+0

您選擇UDP數據報級別的任何特定原因。 –

回答

4

最有可能您發送double S作爲little-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是有損的,所以一些數據包就會丟失。

+1

那就是訣竅!非常感謝你! – wietjes