java - UDP发送和接收

标签 java android udp

我研究了多种方法来做到这一点,但没有任何方法对 Java UDP 数据包有任何帮助/工作。

我的 Android 代码是通过服务启动的,并在新线程上运行。

等待代码:

        try {
            int port = 58452;

            // Create a socket to listen on the port.
            DatagramSocket dsocket = new DatagramSocket(port);

            // Create a buffer to read datagrams into. If a
            // packet is larger than this buffer, the
            // excess will simply be discarded!
            byte[] buffer = new byte[2048];

            // Create a packet to receive data into the buffer
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            // Now loop forever, waiting to receive packets and printing them.
            while (true) {
                // Wait to receive a datagram
                dsocket.receive(packet);

                // Convert the contents to a string, and display them
                String msg = new String(buffer, 0, packet.getLength());
                System.out.println(packet.getAddress().getHostName() + ": "
                        + msg);

                // Reset the length of the packet before reusing it.
                packet.setLength(buffer.length);
            }
        } catch (Exception e) {
            System.err.println(e);
        }

发送代码:

 try {
      String host = "MY PHONES IP";
      int port = 58452; //Random Port

      byte[] message = "LAWL,LAWL,LAWL".getBytes();

      // Get the internet address of the specified host
      InetAddress address = InetAddress.getByName(host);

      // Initialize a datagram packet with data and address
      DatagramPacket packet = new DatagramPacket(message, message.length,
          address, port);

      // Create a datagram socket, send the packet through it, close it.
      DatagramSocket dsocket = new DatagramSocket();
      dsocket.send(packet);
      dsocket.close();
      System.out.println("Sent");
    } catch (Exception e) {
      System.err.println(e);
    }
  }

发送正常,但在 Android 上无法接收。请帮忙!

还有我的 Logcat 输出:http://pastebin.com/Rfw5mSKV

谢谢 -融合

最佳答案

http://systembash.com/content/a-simple-java-udp-server-and-udp-client/

我用过它,它有效!感谢/u/TarkLark 或 Reddit!

关于java - UDP发送和接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28137278/

相关文章:

java - 如何读取属性文件并连接 MySQL 数据库?

java - 无法创建 AVD - Eclipse、MAC OSX、Android 4.4.2

java - 收到的 UDP 消息长度不正确

java - 如何使用 Java MulticastSocket (UDP)?

java - try block 内的 try catch 语句

java - 安卓 3.1 : Unit Testing a Class that Request User Permissions

java - 如何在 Vaadin 中使用 StatusChangeListener 进行验证?

c# - Unity3d:CommandInvokationFailure:Gradle构建失败

android - Firebase(FCM)如何获取 token

c - 从端口 6343 捕获 sflow 数据时,UDP header 长度字段始终为零