【问题标题】:Sending UDP Packets from Matlab to Java将 UDP 数据包从 Matlab 发送到 Java
【发布时间】:2014-05-26 19:28:18
【问题描述】:

我正在尝试将两个双精度值作为 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);
    }
  }
}

【问题讨论】:

    标签: java matlab udp double bytearray


    【解决方案1】:

    UDP 数据包不是 100% 成功的。您的数据包很可能会迟到甚至永远不会到达。您的问题几乎可以由任何原因引起。

    如果您想要有保证的连接,请尝试使用 TCP。 TCP 以速度为代价更可靠。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 2020-09-27
      相关资源
      最近更新 更多