A socket that I'm trying to make a http call is taking too long to respond (around 20 seconds). The code below works it makes an service discovery to an esp8266 module that responds instantly when I access it via browser. I've tried solutions mentioned in this thread but nothing worked, I think that the problem lies before in getInputStream() where the synchronous process holds.
class ESP8266 extends Thread
{
NsdServiceInfo lService;
boolean lToggle = false;
public ESP8266(NsdServiceInfo pService)
{
lService = pService;
}
@Override
public void run() {
while (lServiceActive) {
if (lToggle)
{
lToggle = false;
try {
Socket s = new Socket(lService.getHost(), lService.getPort());
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println("GET /toggle HTTP/1.1");
pw.println("Host: " + s.getInetAddress().getHostName());
pw.println("Connection: close");
pw.println("");
pw.flush();
InputStream stream = s.getInputStream();
byte[] buffer = new byte[1024];
while (stream.read(buffer) > 0)
{
Log.d(TAG, buffer.toString());
}
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void Toggle()
{
lToggle = true;
}
}
Having the code without the getInputStream (shown below) also around 20 seconds to process.
@Override
public void run() {
while (lServiceActive) {
if (lToggle)
{
lToggle = false;
try {
Socket s = new Socket(lService.getHost(), lService.getPort());
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println("GET /toggle HTTP/1.1");
pw.println("Host: " + s.getInetAddress().getHostName());
pw.println("Connection: close");
pw.println("");
pw.flush();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}