0
我有一個Android客戶端和純Java服務器都在同一個子網上,並且我正在從客戶端向服務器發送UDP廣播數據包。對於一些路由器(Netgear,Cisco),服務器愉快地接收數據包,但是對於我的華碩路由器,服務器機器接收到數據包,服務器DatagramSocket沒有。Java DatagramSocket沒有接收到來自某些路由器的UDP廣播
NB在任何情況下,Wireshark都會顯示數據包正在到達服務器計算機。但是當使用Asus路由器時,DatagramSocket似乎看不到它們。爲了簡單起見,服務器只有一個到路由器的以太網連接。
代碼非常標準。
客戶:
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
socket.setSoTimeout(500); // 500 millis
while (isRunning()) {
final InetAddress broadcastAddress = getSubnetBroadcastAddress();
final DatagramPacket outboundPacket = new DatagramPacket(REQUEST_MESSAGE, REQUEST_MESSAGE.length, broadcastAddress, broadcastPort);
socket.send(outboundPacket);
}
} catch (IOException e) {
Log.i(TAG, "Beacon failed", e);
} finally {
if (socket != null) {
socket.close();
}
}
private InetAddress getSubnetBroadcastAddress() throws IOException {
final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final DhcpInfo dhcp = wifi.getDhcpInfo();
if (dhcp == null) {
// No successful DHCP request. Go with best effort.
Log.d(TAG, "#getBroadcastAddress - No DHCP info so using generic broadcast address");
return InetAddress.getByName("255.255.255.255");
}
final int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
final byte[] quads = new byte[4];
for (int k = 0; k < 4; k++) {
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
}
return InetAddress.getByAddress(quads);
}
服務器:
DatagramSocket socket = null;
try {
socket = new DatagramSocket(broadcastPort);
socket.setSoTimeout(LISTENING_TIMEOUT);
socket.setBroadcast(true);
while (keepRunning) {
try {
final byte[] buffer = new byte[1024];
final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receivedPacket);
log.debug("Received packet : " + receivedPacket.toString());
} catch (SocketTimeoutException e) {
log.debug("#run BeaconRunnable socket timed out");
}
}
} catch (IOException e) {
log.warn("Error while receiving message", e);
if (socket != null) {
socket.close();
}
}
是什麼造成DatagramSocket的不看到華碩路由器的UDP廣播包?