我试图拨打http电话的插座响应时间太长(大约20秒)。下面的代码可以对esp8266模块进行服务发现,当我通过浏览器访问它时,它会立即响应。我已经尝试了this线程中提到的解决方案,但没有任何效果,我认为问题出在同步进程所在的getInputStream()之前。
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;
}
}
使用没有getInputStream的代码(如下所示)也需要大约20秒来处理。
@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();
}
}
}
}