The server is on the PC:
sendData = "server msg here".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, ipAddr, portNb);
try {
sendSock.send(sendPacket);
Thread.sleep(1000);
System.out.println("sent msg");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
The fields ipAddr
and portNb
ARE NOT null. In the android application a thread runs:
sendSocket = new DatagramSocket();
sendSocket.setSoTimeout(3000);
sendSocket.setReuseAddress(true);
//...
try {
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
System.out.println("droid now is "
+ new String(receivePacket.getData()));
} catch (IOException e) {
e.printStackTrace();
}
I use the 57111 port on both sides and I have redirected it on the Android emulator on the same port.
In the Android I have hard-coded the IP address of my pc, and on the server side I tried 10.0.2.2, 10.0.2.15 and also the IP address obtained by using the method of the second answer to this question.
I have set a timeout on the Android side for the socket and the trace is :
`02-27 23:12:57.907: W/System.err(13993): java.net.SocketTimeoutException: Try again
02-27 23:12:57.907: W/System.err(13993): at org.apache.harmony.luni.platform.OSNetworkSystem.recv(Native Method)
02-27 23:12:57.917: W/System.err(13993): at dalvik.system.BlockGuard$WrappedNetworkSystem.recv(BlockGuard.java:321)
02-27 23:12:57.927: W/System.err(13993): at org.apache.harmony.luni.net.PlainDatagramSocketImpl.doRecv(PlainDatagramSocketImpl.java:172)
02-27 23:12:57.927: W/System.err(13993): at org.apache.harmony.luni.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:181)
02-27 23:12:57.927: W/System.err(13993): at java.net.DatagramSocket.receive(DatagramSocket.java:402)
02-27 23:12:57.938: W/System.err(13993): at com.example.testinger.ReceiveThread.run(ReceiveThread.java:39)
02-27 23:12:58.987: W/KeyCharacterMap(13993): No keyboard for id 0
02-27 23:12:58.987: W/KeyCharacterMap(13993): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-27 23:12:59.377: W/IInputConnectionWrapper(13993): showStatusIcon on inactive InputConnection
02-27 23:13:00.947: W/System.err(13993): java.net.SocketTimeoutException: Try again
02-27 23:13:01.057: W/System.err(13993): at org.apache.harmony.luni.platform.OSNetworkSystem.recv(Native Method) `
I also tried it on an actual phone and the results are the same. On the Android side the messages do not arrive, the receive method waits until it times out. It has the permissions
- android.permission.INTERNET
- android.permission.ACCESS_NETWORK_STATE
- android.permission.ACCESS_WIFI_STATE
- android.permission.CHANGE_WIFI_MULTICAST_STATE
UPDATE: I tried a simple send-receive program and that didn't work either:the client waits for a packet from the server before being displayed.