Android UDP 无法发送或接收

Android UDP can't send or recive

我正在尝试实现 UDP 服务器和客户端,但没有成功。 对于问题剖析,我只会写关于客户端的内容。我有一个启动下一个 UDP 客户端的按钮:

int UDP_SERVER_PORT = 45455;
private final static int MAX_UDP_DATAGRAM_LEN = 4096;

public void runUdpClient()  {

    String udpMsg = "hello world from UDP client ";
    //  DatagramSocket ds = null;

    try {

        DatagramSocket ds = new DatagramSocket();
        InetAddress serverAddr = InetAddress.getByName("192.168.1.36"); //127.0.0.1
        DatagramPacket dp;
        dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
        Log.v("NEXT", udpMsg);
        ds.send(dp);
        ds.close();

    } catch (SocketException e) {

        e.printStackTrace();

    }catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } catch (Exception e) {

        e.printStackTrace();

    } 

}

在我的清单中,我授予以下权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bolet.simpleudpsenderreceiver" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

在我很久以前测试过的 UDP 服务器中,在我的笔记本电脑中,我从来没有收到任何东西。 phone 不是模拟的 phone,它与我连接在同一网络。我的 udp 服务器正在监听我的端口。

我没有发现任何问题!!!可能是什么? 谢谢!

终于找到了可以正常使用的代码。 将发送方作为异步任务执行:

MsgSender.java

class MsgSender extends AsyncTask<HashMap, Integer, String> {

@Override
protected String doInBackground(HashMap... params) {
    //Retrieve params
    HashMap<String, Object> p = params[0];
    String testServer = (String) p.get("ip");
    String udpMsg = (String)  p.get("msg");
    Integer port = (int) p.get("port");

    InetAddress serverAddr = null;
    DatagramSocket ds = null;
    DatagramPacket dp = null;
    /*
    if (android.os.Build.VERSION.SDK_INT > 9)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }*/

    try {
        serverAddr = InetAddress.getByName(testServer);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    try{
        ds = new DatagramSocket();
    } catch (SocketException e) {
        e.printStackTrace();
    }

    dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, port);

    try {
        ds.send(dp);
    } catch (IOException e) {
        e.printStackTrace();
    }

    ds.close();
    return null;
}

}

MainActivity.java

int UDP_SERVER_PORT = 45455;
int MAX_UDP_DATAGRAM_LEN = 4096;
//String testServer = "192.168.1.39"; //127.0.0.1
String testServer = "10.0.2.2";
String udpMsg = "HELLO!\r\n[=11=]";
int port = 45455;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final EditText ipView = (EditText) findViewById(R.id.ipValue);
final EditText msgView = (EditText) findViewById(R.id.textValue);
final EditText portView = (EditText) findViewById(R.id.portValue);
final Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
        testServer = ipView.getText().toString();
        udpMsg = msgView.getText().toString()+"\r\n[=11=]";
        port = Integer.parseInt( portView.getText().toString() );

        HashMap<String,Object> params = new HashMap<String, Object>();
        params.put("ip", testServer);
        params.put("msg", udpMsg);
        params.put("port", port);
        new MsgSender().execute(params);

    }
});

}

感谢 nyu 的帮助!