我正在尝试在Android中实现基本的数据报套接字。我从网络上可用的示例之一开始:

String messageStr="Hello Android!";
int server_port = 54372;
try {
  DatagramSocket s = new DatagramSocket();
  InetAddress local = null;
  local = InetAddress.getByName("192.168.100.127");
  int msg_length=messageStr.length();
  byte[] message = messageStr.getBytes();
  DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
  s.send(p);
} catch (SocketException e) {
  e.printStackTrace();
} catch (UnknownHostException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}


我已经在AndroidManifest.xml中启用了INTERNET权限:

<uses-permission android:name="android.permission.INTERNET"/>


程序在按下s.send(p)命令时死亡。

我想念什么?这一定是显而易见的。

最佳答案

您将收到一个未捕获的错误:NetworkOnMainThreadException。
您应该在另一个Thread或AsyncTask中做所有网络工作人员。

例如:

class MyThread extends Thread
{
    @Override
    public void run()
    {
        UDPSend();
    }

    void UDPSend()
    {
        String messageStr = "Hello Android!";
        int server_port = 54372;
        try
        {
            DatagramSocket s = new DatagramSocket();
            InetAddress local = null;
            local = InetAddress.getByName("192.168.1.57");
            int msg_length = messageStr.length();
            byte[] message = messageStr.getBytes();
            DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
            s.send(p);
            android.util.Log.w("UDP", "Works fine!");
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            android.util.Log.w("UDP", "Catched here.");
            e.printStackTrace();
        }
    }

}


要在您的主线程中执行线程:new MyThread().start();

更新:

Asynctask中的UDP接收器:
这是应用程序的真实示例。我删除了一些不相关的行。
我向您展示了doInBackgroud,它接收UDP数据包。

@Override
protected Void doInBackground(Void... urls)
{
    DatagramSocket socketUDP;

    try
    {
        socketUDP = new DatagramSocket(5050);
        socketUDP.setSoTimeout(5000);

        // set it to true if you want to receive broadcast packets
        socketUDP.setBroadcast(false);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }

    byte[] buff = new byte[512];
    DatagramPacket packet = new DatagramPacket(buff, buff.length);
    try
    {
        asyncTask_UDP_is_running=true;
        // Keep running until application gets inactive
        while (aplicationActive)
        {
            try
            {
                socketUDP.receive(packet);
                android.util.Log.w("UDP", "got a packet");
            }
            catch (java.net.SocketTimeoutException ex)
            {
                // timeout
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return null;
            }
        }
    }
    finally
    {
        asyncTask_UDP_is_running=false;
    }
    return null;
}


}

08-17 22:58
查看更多