Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter gRPC error - OS Error: Connection refused

I am using protobuf and gRPC to exchange information between a Flutter app and a python server (client in Flutter and the server in python). Server running on 0.0.0.0 and the client is using the IP address of the server machine.

import 'dart:async';
import 'User.pbgrpc.dart';
import 'User.pb.dart';
import 'package:grpc/grpc.dart';

Future<Null> main() async {
  final channel = new ClientChannel('IP_ADDRESS',
      port: 50051,
      options: const ChannelOptions(
          credentials: const ChannelCredentials.insecure()));
  final stub = new StorageClient(channel);

  Test input = new Test();
  input.id = 1;
  try {
    var response = await stub.getPerson(input);
    print('Greeter client received: ${response}');
  } catch (e) {
    print('Caught error: $e');
  }
  await channel.shutdown();
}

if I run this client using dart client.dart everything works fine and I get the expected response. But if I embed this method in a flutter app like:

@override
Widget build(BuildContext context) {

Future<Null> testRPC() async {
  final channel = new ClientChannel('IP_ADDRESS',
      port: 50051,
      options: const ChannelOptions(
          credentials: const ChannelCredentials.insecure()));
  final stub = new StorageClient(channel);

  Test input = new Test();
  input.id = 1;
  try {
    var response = await stub.getPerson(input);
    print('Greeter client received: ${response}');
  } catch (e) {
    print('Caught error: $e');
  }
  await channel.shutdown();
}

testRPC();
...etc
}

I get:

I/flutter (18824): Caught error: gRPC Error (14, Error connecting: SocketException: OS Error: No route to host, errno = 111, address = localhost, port = 45638)

UPDATE: It is working when I run the app with an emulator. So this is error is happening only when using a real device.

like image 339
M20 Avatar asked Sep 16 '25 06:09

M20


2 Answers

If you run AVD(Client) and the backend in same computer, you have to set the base URL instead of "localhost/127.0.0.1" to "10.0.2.2".

Here's the answer in Github.

like image 67
rodrigoherera Avatar answered Sep 19 '25 13:09

rodrigoherera


I had the same error, Flutter app as grpc client and C# as grpc server. The problem was in the server, I was using "localhost" as host parameter, changed to "0.0.0.0" and now is running fine.

like image 42
Juan Córdova Avatar answered Sep 19 '25 13:09

Juan Córdova