为什么我的应用程序无法在 Hotsport 网络中使用 UDP 接收数据?但我的应用程序可以在普通 Wi-Fi 网络中使用 UDP 接收数据。发件人的代码是:
@Override
public void run() {
super.run();
DatagramPacket dataPacket = null;
try {
udpSocket = new DatagramSocket(DEFAULT_PORT);
dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
while (isRunning) {
String address = getLocalIPAddress();
if (address != null) {
byte[] data = address.getBytes();
dataPacket.setData(data);
dataPacket.setLength(data.length);
dataPacket.setPort(DEFAULT_PORT);
InetAddress broadcastAddr;
broadcastAddr = InetAddress.getByName("255.255.255.255");
dataPacket.setAddress(broadcastAddr);
try {
Log.i(DazzleApplication.TAG,"Sending---->"+address);
sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (udpSocket != null)
udpSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
接收方代码为:
public void run() {
DatagramPacket udpPacket=null;
byte[] data=null ;
try {
udpSocket = new DatagramSocket(43708);
udpSocket.setSoTimeout(3000);
data= new byte[256];
udpPacket= new DatagramPacket(data, 256);
} catch (SocketException e) {
e.printStackTrace();
System.out.println(e.toString());
}
while (start) {
System.out.println("DazzleTest Receive.....");
try {
udpSocket.receive(udpPacket);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}
if (udpPacket.getLength() != 0) {
String codeString = new String(data, 0,
udpPacket.getLength());
Message msg = new Message();
msg.obj = codeString;
mH.sendMessageDelayed(msg, 1000);
System.out.println("receiver--->"+codeString);
}else{
System.out.println("receiver null");
}
}
if (udpSocket != null) {
udpSocket.close();
}
}
为什么?谁能解释一下这个案子?UDP不能在热点中工作??
更新以下信息: 套接字的发送者在打开 Hotspot 的 HTC HD 中运行。它可以捕获异常:java.net.SocketException: Network is unreachable: connect
.