Flutter HTTP Client桌面与Web平台连接延迟差异问题求助
问题背景
我使用Flutter的http包处理本地网络中通过mDNS发现的ESP32 Web服务器请求,应用主要面向Web平台,同时需要支持Linux桌面开发环境。
Web构建时,首次HTTP请求通常耗时5-10秒,但后续所有请求(哪怕长时间闲置后)都能在毫秒级完成;而Linux桌面构建在闲置几秒后,下一次请求又会变得极慢。
用于计时请求的代码片段(client为类成员):
ElevatedButton( onPressed: () async { print("Start stopwatch"); final stopwatch = Stopwatch()..start(); var response = await _client.get(Uri.http('MYDOMAIN.local', 'sys/')); stopwatch.stop(); print( 'Stop stopwatch, elapsed ms ${stopwatch.elapsedMilliseconds}'); print('Response status: ${response.statusCode}'); print('Response body: ${response.body}'); }, child: const Text('http.Client() request'), ),
我希望让桌面构建也能实现Web端的低延迟表现。
排查结论与解决方案
经排查,该问题属于mDNS解析延迟,与Flutter本身无关。针对Linux(以Ubuntu 20.04为例)的.local域名解析慢问题,可通过以下方式解决:
- 调整nsswitch.conf配置,让系统优先使用mDNS解析
.local域名:
编辑/etc/nsswitch.conf文件,找到hosts行,将mdns4_minimal [NOTFOUND=return]移到dns前面,修改后示例:hosts: files mdns4_minimal [NOTFOUND=return] dns myhostname - 确保avahi-daemon服务正常运行:
执行以下命令启用并启动服务:sudo systemctl enable avahi-daemon sudo systemctl start avahi-daemon - 添加静态域名映射(彻底规避mDNS查询):
在本地/etc/hosts文件中手动添加ESP32的静态IP与.local域名的映射,示例:
这样系统无需每次通过mDNS查询,直接从hosts文件获取地址,彻底解决延迟问题。192.168.x.y MYDOMAIN.local
内容的提问来源于stack exchange,提问作者Vinci
相关产品推荐
相关产品推荐

