使用 Java 的 Android 应用程序 - udp 字符串不发送

我已经开始在 android studio 上使用 JAVA,我正在尝试创建一个简单的应用程序,它将向我的服务器发送 udp 字符串。


一切似乎都在应用程序中工作(当我按下按钮时,我可以看到它被按下,当我使用 android studio 和调试时 - 该功能正在工作,我没有得到任何异常)。


我已经检查过,我的服务器正在侦听该端口(其他应用程序正在发送到该端口 - 并且它正在工作)。


但我不认为应用程序正在发送给它。


这就是我所拥有的:


btnAction.setOnClickListener(new View.OnClickListener() {

    @override

    public void onClick(View v) {

        try {

            String messageStr = "test!";

            int server_port = 1111;

            DatagramSocket s = new DatagramSocket();

            InetAddress local = InetAddress.getByName("My.Public.Server.IP");

            int msg_length = messageStr.length();

            byte[] message = messageStr.getBytes();

            DatagramPacket p = new DatagramPacket(message, msg_length, local,server_port);

            s.send(p);

        } catch (Exception e) {

        }

    }

}

知道出了什么问题吗?


杨__羊羊
浏览 158回答 1
1回答

尚方宝剑之说

您必须在清单中拥有互联网权限<uses-permission android:name="android.permission.INTERNET"/>您必须在不同的线程中运行网络相关任务(而不是在主线程中)您的代码将如下所示:btnAction.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; @override&nbsp; &nbsp; public void onClick(View v) {&nbsp; &nbsp; &nbsp; &nbsp; new Thread("thread_udp"){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String messageStr = "test!";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int server_port = 1111;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DatagramSocket s = new DatagramSocket();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InetAddress local = InetAddress.getByName("My.Public.Server.IP");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int msg_length = messageStr.length();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] message = messageStr.getBytes();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DatagramPacket p = new DatagramPacket(message, msg_length, local,server_port);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s.send(p);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }.start()&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java