服务器在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();
}
字段ipAddr
和portNb
不为空。在 android 应用程序中运行一个线程:
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();
}
我在两边都使用了 57111 端口,并在同一端口上的 Android 模拟器上将其重定向。
在Android中我已经硬编码了我的电脑的IP地址,在服务器端我尝试了10.0.2.2、10.0.2.15以及使用此问题第二个答案的方法获得的IP地址。
我在 Android 端为套接字设置了超时,跟踪是:
`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) `
我也在实际的手机上试过,结果是一样的。在 Android 端,消息没有到达,receive 方法一直等到超时。它有权限
- android.permission.INTERNET
- android.permission.ACCESS_NETWORK_STATE
- android.permission.ACCESS_WIFI_STATE
- android.permission.CHANGE_WIFI_MULTICAST_STATE