P.T.
P.T.

Reputation: 25177

Cannot connect to my HTTP server running on my Android phone

I'm trying to run a small, custom HTTP server embedded in my Android application (to aid in debugging the app). However, I cannot reliably to connect to the HTTP server from my desktop web browser when the server is running on my Android 2.3.4 phone.

I know the HTTP server code works (at least the basics), because one time the connection went through fine. And the code works reliably when run on my desktop (my app is a libgdx-based, pure Java app that can be built for Windows or for Android).

I have the Android permissions correct, because I was getting the PermissionDenied fault (when setting up the socket listener) thrown before I added the android:name="android.permission.INTERNET" permission. The server-side code runs in its own thread and boils down to:

ServerSocket ss = new ServerSocket(serverPort);
Socket clientSocket = ss.accept();

I'm using port 8080. (I tried port 80 but hit the must-be-root-below-port-1024 "feature" of Linux).

The LogCat output looks fine. My app just prints its "listening on port 8080" message and no exceptions seem to be thrown.

Network connectivity seems fine (browsing the internet from the phone is working, and I can ping the phone from desktop). I'm using WiFi, not 3G.

Upvotes: 2

Views: 2195

Answers (1)

P.T.
P.T.

Reputation: 25177

I think I found it. I was missing a call to:

ss.setReuseAddress(true);

after creating the server socket. This means each restart of the app (pause/resume, too) was (silently?) failing to create server socket because the socket was marked as 'in use' for a bit. This explains why it was so unreliable (only the very first run, or running after a long enough wait would work ...)

I found it by staring at the code linked to from this blog entry.

Upvotes: 1

Related Questions