udp6在编写android udp服务器时关闭

时间:2012-04-27 03:37:26

标签: android udp virtualbox ipv6

我正在Android 4.0中编写 UDP服务器程序(api 15) 程序启动时,我无法连接到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侦听套接字?

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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();
    }
};