Search code examples
dartflutterprotocol-buffersgrpc

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.


Solution

  • In my case, it was a firewall problem. Running systemctl stop firewalld on the server solved it.