我试图在热点上的两个Android设备之间广播udp数据包。
我有一个设置热点的客户端,以及一个连接到热点的服务器。从客户端发送包并在服务器上接收该包正在运行。但是当我尝试从服务器回复时,我收到一个SocketException,说网络无法访问。我检查了IP地址和端口号,两者都应该是正确的(我假设端口是正确的,因为它是从数据包本身获取的)。
服务器和客户端的代码如下。任何人都可以看到代码出错的地方,或者它只是一个网络连接问题吗?
客户端:
try {
//Open a random port to send the package
c = new DatagramSocket();
c.setBroadcast(true);
byte[] sendData = "DISCOVER_MV_REQUEST".getBytes();
try {
InetAddress addr = getIpAddress();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, getBroadcast(addr), 8888);
c.send(sendPacket);
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
// Broadcast the message over all the network interfaces
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue; // Don't want to broadcast to the loopback interface
}
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null) {
continue;
}
// Send the broadcast package!
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
c.send(sendPacket);
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
}
}
//Wait for a response
byte[] recvBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
c.receive(receivePacket);
//Check if the message is correct
String message = new String(receivePacket.getData()).trim();
if (message.equals("DISCOVER_MV_RESPONSE")) {
//DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
Log.v("SOCKET", "got correct response");
c.close();
return "correct";
} else {
c.close();
Log.v("SOCKET", "wrong response");
return "wrong";
}
} catch (Exception e) {
c.close();
e.printStackTrace();
return null;
}
服务器:
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
socket = new DatagramSocket(8888, InetAddress.getByName("0.0.0.0"));
socket.setBroadcast(true);
while (true) {
//Receive a packet
byte[] recvBuf = new byte[15000];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet);
//See if the packet holds the right command (message)
String message = new String(packet.getData()).trim();
if (message.equals("DISCOVER_MV_REQUEST")) {
byte[] sendData = "DISCOVER_MV_RESPONSE".getBytes();
//Send a response
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
socket.send(sendPacket); //where the error happens
socket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}