简体   繁体   English

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

[英]Android application with Java - udp string doesn't send

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. 我已经开始在Android Studio上使用JAVA,并且正在尝试创建一个简单的应用程序,它将向我的服务器发送udp字符串。

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). 一切似乎都在应用程序中正常工作(当我按下按钮时,我可以看到它被按下了,而当我使用android studio进行调试时-该功能正在运行,我没有任何异常)。

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. You must have internet permission in manifest <uses-permission android:name="android.permission.INTERNET"/> 您必须在清单<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()

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM