是什么导致多播消息在 wifi 重启后不立即流动

What is causing multicast messages not to flow immediately after wifi restart

我有一个 Android 应用程序可以创建 MulticastSocket、加入 MC 组并从本地 wifi 网络上的另一台机器接收消息。

MulticastSocket socket = new MulticastSocket(null); // Create an unbound socket.
socket.setSoTimeout(LISTEN_TIMEOUT_MILLIS);
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(listenPort)); // Bind to the configured multicast port

final WifiManager.MulticastLock lock = wifiManager.createMulticastLock("my_lock");
lock.acquire();

socket.setNetworkInterface(networkInterface);
socket.joinGroup(multicastGroup);
while (true) {
    socket.receive(packet);
    // Do something with the packet
    // Handle timeout etc.
    // Handle change of network interface by leaving group, setting netIntf and joining group again.
}
socket.leaveGroup(multicastGroup);
socket.close();

lock.release();

在大多数 Android 设备(华为、三星)上运行良好,但在某些设备 (Pixel3) 上运行良好,如果设备上的 WiFi 关闭然后再次打开,而应用会看到 Wifi 连接上线后,最多可能需要 14 分钟(变化很大)才能再次开始接收 MC 消息。

即使丢弃 Socket 并创建一个新的 MCSocket 也不能​​减轻延迟。

但它必须是 JVM 中保存的某种状态,因为应用程序重新启动会导致它立即连接。

感觉好像有一些租约正在为 MC 连接保留,只在一个时钟周期内更新。

所以我的问题是:

  1. 是什么导致 MC 消息在 WiFi 连接恢复并创建一个新的 MCSocket 听这个。
  2. 如何确保及时恢复消息流?

我注意到您更新了问题以包含 WifiManager.MulticastLock

我想知道您是否在 Wifi 连接恢复时重新获取锁,SO 上的一些 post 暗示这是必要的。

我注意到以下评论 post:

回复:

it turns out that your multicast lock is destroyed when the connectivity goes away (the long delay was me rewriting my code three times before I figured this out). So, you have to reacquire the lock every time the connection comes back