[英]Sending UDP Packets from Matlab to Java
我正在嘗試將兩個雙精度值作為UDP數據包從Matlab發送到Java程序,但是我無法同時訪問它們。任何人都可以向我建議如何實現。
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.io.*;
import java.nio.*;
import java.lang.*;
public class UDPReceive {
public static void main(String args[]) {
try {
int port = 25001;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048];
// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
dsocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
Double x = ByteBuffer.wrap(buffer).getDouble();
System.out.println(packet.getAddress().getHostName() + ": "
+" "+x+" ");
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
UDP數據包並非100%成功。 您的包裹很有可能遲到,甚至永遠不會到達。 您的問題可能是由幾乎所有原因引起的。
如果想要保證連接,請嘗試使用TCP。 TCP以速度為代價更加可靠。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.