Flutter - 如何实现网络服务发现

Yog*_*wla 3 dart flutter

我想发现正在运行暴露于本地网络的指定服务的设备,但我不知道如何做。例如,我想要运行服务“_googlecast._tcp.”的设备的本地 IP 地址和端口号。

Flutter 有什么办法可以实现这一点吗?

提前致谢

小智 5

检查多播 DNS 包:一个 Dart 包,用于通过多播 DNS (mDNS)、Bonjour 和 Avahi 进行服务发现。本质上,创建一个 mDNS 客户端并获取该服务的 PTR 记录,如下所示:

const String name = '_googlecast._tcp.local';
  final MDnsClient client = MDnsClient();
  await client.start();
  // Get the PTR recod for the service.
  await for (PtrResourceRecord ptr in client
      .lookup<PtrResourceRecord>(ResourceRecordQuery.serverPointer(name))) {
    // Use the domainName from the PTR record to get the SRV record,
    // which will have the port and local hostname.
    // Note that duplicate messages may come through, especially if any
    // other mDNS queries are running elsewhere on the machine.
    await for (SrvResourceRecord srv in client.lookup<SrvResourceRecord>(
        ResourceRecordQuery.service(ptr.domainName))) {
      // Domain name will be something like "io.flutter.example@some-iphone.local._dartobservatory._tcp.local"
      final String bundleId =
          ptr.domainName; //.substring(0, ptr.domainName.indexOf('@'));
      print('Dart observatory instance found at '
          '${srv.target}:${srv.port} for "$bundleId".');
    }
  }
  client.stop();

  print('Done.');
Run Code Online (Sandbox Code Playgroud)

  • 如果在 Android 上,则从以下内容开始:`var factory = (dynamic host, int port, {bool reuseAddress, bool reusePort, int ttl}) { return RawDatagramSocket.bind(host, port, reuseAddress: true, reusePort: false, ttl: 1 );}; var client = MDnsClient(rawDatagramSocketFactory:factory);`(参见https://github.com/flutter/flutter/issues/27346#issuecomment-594021847) (5认同)