使用同一个套接字发送多个HTTP请求



我正在尝试发送多个http get请求到我的esp32服务器,同时使用相同的套接字,但我的程序在从服务器打印出响应后停止。(这是我写的一个小示例代码,它应该打开和关闭连接到esp的led)

客户端代码:


URL url;
String hostname;
Socket socket;

public HttpClient() throws UnknownHostException, IOException, InterruptedException {
        url = new URL("http://192.168.178.56");
        hostname = url.getHost();
        int port = 80;
 
  
        socket = new Socket(hostname, port);
        PrintWriter output = new PrintWriter(socket.getOutputStream());
        InputStream input = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        
        for(int i=1; i<50; i++)
        {
            String x = i%2==0 ? "on" : "off";
            
            System.out.println("h1");
            
                    output.write(
                    String.format(
                        "GET /" + x + " HTTP/2rn"
                      + "Host: " + hostname + "rn"
                      + "Connection: keep-alivern"
                      + "rn"
                        )
                     );
                output.flush();
            
                    System.out.println("h2");
            
                    String line;
                    while ((line = reader.readLine()) != null) {
                         System.out.println(line);
                    }
            
                    System.out.println("h3");
                        
                        Thread.sleep(200);
        } 
}

,这是控制台输出:

h1
h2
HTTP/1.1 200 OK
Content-Length: 2
Content-Type: text/plain
Connection: close
Accept-Ranges: none

可以看到,它总是停在"System.out.println("h3");">

我试着遵循一个类似讨论的答案,但没有成功:如何在java中使用相同的套接字连接做多个http请求?

是我忽略了什么,还是我应该采取完全不同的方法?

                    "GET /" + x + " HTTP/2rn"

这甚至不是一个有效的HTTP请求。做HTTP/2是一个比仅仅使用HTTP/2作为协议字符串而不是HTTP/1.1或HTTP/1.0复杂得多的协议。

  Connection: close

服务器明确表示将在响应后关闭连接。因此,在同一连接上不会接受更多的请求。

我正在尝试发送多个http get请求到我的esp32服务器,而使用相同的套接字,

为了在同一个连接上发送多个请求,服务器必须支持这个。不能强迫服务器这样做。即使支持持久连接(HTTP keep-alive),客户端和服务器也可以在请求+响应完成后随时关闭连接。

在微处理器中使用最小的HTTP栈并不罕见控制器不需要实现持久连接,因为它更复杂,代码也更多。

最新更新