Tuesday, 3 January 2023

Why the web server started on Android cannot be accessed on the PC

I am using flutter to open an http server on Android

import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:jaguar/serve/server.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Http Server',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Jaguar _server;

  @override
  void initState() {
    super.initState();
    init();
  }

  @override
  void dispose() {
    super.dispose();
    _server.close();
  }

  void init() async {
    try {
      _server = Jaguar(port: 7777);
      _server.get('/', (ctx) => 'Hello world!');
      await _server.serve();
    } catch (e) {
      print("Something went wrong while creating a server...");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          var url = Uri.parse("http://localhost:7777");
          var response = await http.get(url);
          print('Response status: ${response.statusCode}');
          print('Response body: ${response.body}');
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

PC and Android real machine connected to the same WIFI

Test the app on the real machine and click add to get the expected results, but I cannot access this http service on the PC

$ curl http://192.168.9.102:7777
curl: (7) Failed to connect to 192.168.9.102 port 7777 after 2048 ms: Connection refused

I'm not sure what's causing it, my guess is that Android blocks all port connections in order to protect the phone's security, if so how do I expose port 7777 to the LAN



from Why the web server started on Android cannot be accessed on the PC

No comments:

Post a Comment