问题
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:
- You must have internet permission in manifest
<uses-permission android:name="android.permission.INTERNET"/>
- 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