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. Everything seems to be working in the ap
Solution 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()
}
}
Post a Comment for "Android Application With Java - Udp String Doesn't Send"