Flutter: WebSocketChannelException / HttpException when connecting to ESP32 AP on Android (Ping works, connection fails)

1 day ago 2
ARTICLE AD BOX

I am developing a Flutter app to communicate with an ESP32 acting as an Access Point (AP). The ESP32 has a static IP 192.168.1.1 and is running an HTTP server and a WebSocket server on port 80.

The Problem: My Android device (Hisense H50, Android 10) connects to the ESP32 WiFi. I can successfully ping the ESP32 from the device, but when I try to connect via web_socket_channel or http package, I get the following error: Unhandled Exception: WebSocketChannelException: HttpException: Connection closed before full header was received, uri = http://192.168.1.1:0 (or sometimes Connection Refused).

What I have tried:

AndroidManifest.xml: Added INTERNET, ACCESS_FINE_LOCATION, and ACCESS_NETWORK_STATE permissions.

Cleartext: Enabled android:usesCleartextTraffic="true" in the manifest.

Mobile Data: I turned off mobile data to force the traffic through WiFi.

Network Security Config: Added a network_security_config.xml to allow cleartext for 192.168.1.1.

Testing: A third-party "WebSocket Tester" app also fails with "Connection Refused".

Flutter Code Snippet:

Dart

final uri = Uri.parse("ws://192.168.1.1:80"); channel = WebSocketChannel.connect(uri); channel!.stream.listen((event) => print(event), onError: (e) => print(e));

Firmware (ESP32): The ESP32 is using WiFi.softAP and server.listen(80).

Why is the connection being refused or closed immediately if the device is reachable via ping? Is there an Android-specific restriction for local non-internet networks that I'm missing?

Read Entire Article