通过 UDP 数据包从 matlab 发送 double 到 java
Sending double from matlab to java via UDP-packets
我正在尝试将双打从 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);
}
}
我正在获取值,但它们确实没有意义...
很可能您将 double
发送为小端,但 ByteBuffer 假定 "network order" 为大端。
尝试
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 是有损的,因此会丢失一些数据包。
我正在尝试将双打从 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);
}
}
我正在获取值,但它们确实没有意义...
很可能您将 double
发送为小端,但 ByteBuffer 假定 "network order" 为大端。
尝试
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 是有损的,因此会丢失一些数据包。