Android application with Java - udp string doesn't send

冷暖自知 提交于 2019-12-11 15:44:01

问题


I have started working with JAVA on android studio and I'm trying to create a simple application that will send to my server a udp string.

Everything seems to be working in the application (when I press the button I can see it been pressed , and when I use android studio and debug - the function is working, I don't get any exceptions).

I have checked and my server is listening to the port (other applications are sending to this port - and it's working).

But I don't think the application is sending to it.

This is what I have :

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) {
        }
    }
}

Any idea what is wrong?

Thanks in advance.


回答1:


  1. You must have internet permission in manifest <uses-permission android:name="android.permission.INTERNET"/>
  2. You have to run network related task in a different thread (not in the main thread)

Your code will look like:

btnAction.setOnClickListener(new View.OnClickListener() {
    @override
    public void onClick(View v) {
        new Thread("thread_udp"){
            public void run(){
                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) {
                    e.printStackTrace()
                }
            }
        }.start()

    }
}


来源:https://stackoverflow.com/questions/57712357/android-application-with-java-udp-string-doesnt-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!