问题描述
我已经开始在android studio上使用JAVA,并且我正在尝试创建一个简单的应用程序,该应用程序将向我的服务器发送一个udp字符串.
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进行调试时-该功能正在起作用,我没有任何异常).
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.
这就是我所拥有的:
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) {
}
}
}
有什么想法吗?
谢谢.
推荐答案
- 您必须在清单
< uses-permission android:name ="android.permission.INTERNET"/>
中具有互联网许可 - 您必须在其他线程(而不是主线程)中运行与网络相关的任务
您的代码如下:
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()
}
}
这篇关于具有Java的Android应用程序-udp字符串不发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!