0

以下代码在 android 中进行了尝试,它没有使用直接 WI-FI 接收任何数据,这意味着发送者(桌面应用程序)和 Android 应用程序都在同一个网络上。发件人应用程序知道 WI-FI 平板电脑的 IP 地址并将数据发送到该地址。

但是,以下代码可以作为独立的 java 应用程序运行。接收代码不使用 InetAddress 地址;Android中是否需要它。有人可以发布通过 WI-FI 接收 udp 数据的示例。

发送者知道平板电脑的 IP 地址,将数据发送到平板电脑。发送方和接收方都使用相同的端口。

我正在尝试获取数据包并从数据包中获取内容。我不会向发件人回复任何内容。我需要将任何内容回显给发件人吗?我还需要 WI-FI 管理员吗?

import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class NetworkReceiver {

  static boolean isFinish = false;

    try {

         DatagramSocket s = new DatagramSocket(2010);
         System.out.println("setting up port");
         byte[] data = new byte[12];

        while (!isFinish) 
        {          
            System.out.println("creating datagram");
            DatagramPacket p = new DatagramPacket(data, data.length);
            s.receive(p);
            System.out.println("got packet");
            ByteBuffer bb = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN);
            bb.put(data);
            bb.rewind();
            System.out.println(bb.getFloat());
            System.out.println(bb.getFloat());
            System.out.println(bb.getFloat());

         }
    } catch (IOException e) {
      e.printStackTrace();
    }

}
4

1 回答 1

0

However the following code works fine running it as a standalone java application.

I'm assuming that you ran the sender and receiver applications from two separate PCs connective to the same WIFI router correct?

I am trying to get a data packet and get the contents out of the data packet. I am not echoing anything back to the sender. Do I need to echo anything back to the sender. Also do I need a WI-FI manager?

No, you don't need to echo or respond to a received packet in any way.

Your receiver code looks ok enough that it should at least receive the 1st packet sent. Android would have complained if your AndroidManifest.xml permissions didn't allow for network access.

All I can suggest until you confirm that your sender app (you should include the code) is actually sending packets out into the WIFI network, is to make sure you can ping your tablet from the PC. Then install Wireshark on your sender PC and take a look at the UDP packets issued when it runs. Check the destination address and port. Make sure they look like they should reach your tablet.

Finally, I'm assuming again that you're not trying to multicast UDP since you've specified the tablet's IP address in your sender. If you are, you need to get a multicast lock with the WifiManager.

于 2013-09-24T18:34:28.370 回答