1

当程序启动时,我正在 Android 4.0 (api 15) 中编写 UDP 服务器程序,我无法连接到 android 中的UDP服务器

环境

virtualbox, android x84 4.0, ping to/from virtualbox-android are ok,

UDP服务器代码

DatagramSocket ds = new DatagramSocket(9101);
<uses-permission android:name="android.permission.INTERNET" />

android中的netstat显示

udp6    0    0    :::9101    :::*    CLOSE

如何制作普通的 IPv4 UDP 监听套接字?

4

2 回答 2

0

您无法在主线程中接收或执行网络流量。

您必须创建一个单独的可运行线程来执行此操作:

new Thread(new Runnable() {
    public void run() {
    try {
           if (clientsocket == null) {
        clientsocket = new DatagramSocket(null);
            clientsocket.bind(new InetSocketAddress("0.0.0.0", 1337));
        clientsocket.setBroadcast(true);
       }
           byte[] receivedata = new byte[1024];
       while (true) {
        DatagramPacket recv_packet = new DatagramPacket(
        receivedata, receivedata.length);
        clientsocket.receive(recv_packet);
            alertMessage = new String(recv_packet.getData());
        InetAddress ipaddress = recv_packet.getAddress();
        int port = recv_packet.getPort();
        String msg = "RECEIVED UDP MSG FROM " + ipaddress.toString() + ":" + Integer.toString(port) + " :" + alertMessage;  Log.d("UDP", msg);
        myHandler.post(alertMsg);
        }
    } catch (Exception e) {
        Log.e("UDP", "S: Error", e);
    }
      }
}).start();

然后在一个单独的类代码中,可能会干扰主 UI 的可运行任务。

final Runnable alertMsg = new Runnable() {
    public void run() {
        Toast.makeText(getApplicationContext(), alertMessage, Toast.LENGTH_LONG).show();
    }
};
于 2013-10-18T09:21:35.260 回答
0

尝试

DatagramSocket ds = new DatagramSocket(9101, InetAddress.getByName("192.168.1.1"));

看看是否可行。您也可以先创建套接字,然后再绑定它,例如:

DatagramSocket ds = new DatagramSocket(null);
ds.bind(new InetSocketAddress("192.168.1.1", 9101));
于 2012-04-27T13:18:04.143 回答