I have a http server code (I tried both TJWS or NanoHTTPD), the client from the same application would connect to server running on port 8080 or whatever.
I am starting server object in a separate AsyncTask so it should be okay.
While NanoHTTPD completely failed to start other ways I can see from TJWS logs, it says something like;
server listening on 0.0.0.0/0.0.0.0 port:0 localport:8080
This means server started successfully, first question is 0.0.0.0 bind address acceptable? I mean it should be 127.0.0.1 instead? sorry if that is a noob question.
When I connect to my emulator using adb shell and run netstat, I can see the following lines
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:5037 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5555 0.0.0.0:* LISTEN
tcp 0 0 10.0.2.15:5555 10.0.2.2:52132 ESTABLISHED
tcp6 0 0 :::8080 :::* LISTEN
By googling I learned that 0 :::8080 means server is listening on ipv6 and ipv4 both and that is okay.
But from my client code when i tried to access it continues to wait for eternity.
my httpClient Code
try {
URL url = new URL("http://0.0.0.0:"+8080+"/media");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null){
Log.d("server", line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For the server, the address 0.0.0.0 is like a wildcard and means, it is listening on all IP addresses the device has.
For the client, you need to use a real IP address like 127.0.0.1
After debugging a little I found that problem is not where client opens a connection but issue was at where server was starting it never returned onPostExecute() method, but after wrapping my server start code inside a Runnable
new Thread(new Runnable() {
@Override
public void run() {
Log.d("server", "server starting on port: " + port);
srv.serve();
}
}).start();
it Works!!
Server is a infinite loop so does it have to be started from inside thread? I thought AsyncTask can handle that?
Its also worth mentioning that client side connection must also be wrapped inside AsyncTask
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.