Flutter/Dart下gRPC连接异常:指定端口未生效问题求助
Flutter/Dart gRPC连接被拒绝(指定端口却显示随机端口)解决方案
问题详情
运行Flutter/Dart gRPC客户端时触发如下错误:
gRPC Error (code: 14, codeName: UNAVAILABLE, message: Error connecting: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 58434, details: null, rawResponse: null, trailers: {})
代码中明确指定连接端口为9991,但错误日志显示实际连接的是随机端口58434,导致连接被拒绝。
已知信息
- gRPC服务器已在
localhost:9991正常启动,React/TypeScript客户端可成功连接 - 使用Mac设备,尝试替换
localhost为127.0.0.1或0.0.0.0均无效
客户端代码
import 'dart:developer'; import 'package:grpc/grpc.dart'; import 'package:my_app/gen/grpc/auth/v1/auth.pbgrpc.dart'; Future<void> useLogin() async { final req = SigninRequest( email: 'xxx@gmail.com', password: 'hogehoge', organizationId: 'xxxxx'); final channel = ClientChannel( 'localhost', port: 9991, options: const ChannelOptions( connectTimeout: Duration(seconds: 30), connectionTimeout: Duration(seconds: 30), credentials: ChannelCredentials.insecure(), ) ); final options = CallOptions( timeout: const Duration(seconds: 30), ); final client = AuthServiceClient(channel, options: options); try { final response = await client.signin(req); log("success!!!"); log(response.toString()); } catch (e) { log("error!!!"); log(e.toString()); } }
可行解决方案
1. 适配模拟器/真机的网络映射
- iOS模拟器:重启模拟器清除缓存(偶尔会出现
localhost映射异常) - Android模拟器:
localhost指向模拟器自身,需替换为10.0.2.2(Android官方提供的宿主机映射地址),或者直接使用Mac的局域网IP(如192.168.1.xx)
2. 修正服务器绑定地址
确保gRPC服务器绑定到0.0.0.0而非仅127.0.0.1,这样才能接受来自模拟器/真机的连接请求。大部分服务器默认只绑定本地回环地址,导致外部进程无法访问。
3. 排查防火墙与代理干扰
- 临时关闭Mac防火墙测试,或在防火墙设置中允许gRPC服务器和Flutter应用的网络权限
- 若开启了VPN或系统代理,暂时关闭后重试,避免代理拦截gRPC连接
4. 禁用客户端代理
显式禁用gRPC客户端的代理设置,防止系统代理干扰连接:
final channel = ClientChannel( '你的Mac局域网IP', port: 9991, options: ChannelOptions( credentials: ChannelCredentials.insecure(), httpClient: HttpClient()..findProxy = (uri) => 'DIRECT', // 强制不使用代理 ), );
5. 同步gRPC版本兼容性
检查pubspec.yaml中grpc包的版本,升级到最新稳定版确保与服务器端兼容:
dependencies: grpc: ^3.2.0 # 替换为当前最新稳定版
执行flutter pub get完成更新
内容的提问来源于stack exchange,提问作者Nanano
相关产品推荐
相关产品推荐

