UDP 发送和接收

Posted

技术标签:

【中文标题】UDP 发送和接收【英文标题】:UDP Sending and Receiving 【发布时间】:2015-01-25 14:06:56 【问题描述】:

我已经研究了多种方法来做到这一点,但对于 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

谢谢 -融合

【问题讨论】:

你试过在同一台机器上接收吗?确定它是正确的 ip 并且您的路由器没有过滤端口吗?乍一看,代码似乎没问题... 是的,我已经尝试了大约 10 个端口。我会在同一台机器上试试! 【参考方案1】:

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

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

【讨论】:

以上是关于UDP 发送和接收的主要内容,如果未能解决你的问题,请参考以下文章

发送和接收UDP数据[重复]

在一个应用程序中发送和接收 UDP 数据包

发送和接收UDP数据包

UDP接收和发送Matlab

UDP中接收和发送数据

简单的UDP套接字代码,发送和接收消息