服务器在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地址{{3问题。
我在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端,消息没有到达,接收方法等待它超时。它具有权限
答案 0 :(得分:0)
您的服务器或端口似乎无法从设备访问。您是否在计算机上运行任何HTTP Server,您可以使用浏览器对其进行测试。
或者您可以使用代码 - 请参阅下文 - Android: How to check if the server is available? How to test if a remote system is reachable