I am making a very simple app in which I send a text string from java program on my PC and I am trying to receive same string from my android app in emulator.
This is my activity(server):
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appstart);
tv = (TextView) findViewById(R.id.textView1);
try {
DatagramSocket clientsocket = new DatagramSocket(9876);
byte[] receivedata = new byte[1024];
DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
Log.d("UDP", "S: Receiving 1 sec...");
clientsocket.receive(recv_packet);
String rec_str = new String(recv_packet.getData());
tv.setText(rec_str);
Log.d(" Received String ", rec_str);
InetAddress ipaddress = recv_packet.getAddress();
int port = recv_packet.getPort();
Log.d("IPAddress : ", ipaddress.toString());
Log.d(" Port : ", Integer.toString(port)); clientsocket.close();
} catch (Exception e) {
Log.e("UDP", "S: Error", e);
}
}
Here is my PC client java code:
public static void main(String args[]) throws Exception
{
while(true)
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
System.out.println(IPAddress.getHostName());
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,9876);
clientSocket.send(sendPacket);
System.out.println(sendPacket.getPort());
clientSocket.close();
}
}
However the app does not receive anything, but ot throws an exception on onReceive() function in android app….
Does any one knows why?
You get android.os.NetworkOnMainThreadException because you are running network methods on your main thread, this will make your app not responsive. Try putting it into a separate thread or…in this case, perhaps a Service that your Activity can bind to.
(See How to fix android.os.NetworkOnMainThreadException? for an example)
IF (NOT RECOMMENDED) you only need to test your UDP service, you can set your API requirement to 7 or below OR disable the network on main thread policy, you will not receive a exception. However, your app will be highly unresponsive.