HTTP短连接的通信实验

119 阅读1分钟

HTTP短连接的通信实验

1. 概念

HTTP属于TCP/IP模型中的应用层协议,HTTP长连接和HTTP短连接指的是传输层TCP连接是否被多次使用

我理解的HTTP长连接和TCP长连接的概念
TCP本身就是长连接
HTTP本身不涉及网络,他只是应用层协议

2. 测试步骤

2.1 部署自己的服务器应用

<build>
   <plugins>
       <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
           <version>${springboot.version}</version>
           <configuration>                <mainClass>com.crazymakercircle.netty.http.echo.HttpEchoServer</mainClass>
               <includeSystemScope>true</includeSystemScope>
           </configuration>
           <executions>
               <execution>
                   <goals>
                       <goal>repackage</goal>
                   </goals>
               </execution>
           </executions>
   </plugin>
      
   <finalName>NettyHttpServerDemo</finalName>
</build>


打包scp NettyHttpServerDemo.jar root@1.117.109.40:/tmp
java -jar NettyHttpServerDemo.jar

2.2. 测试

while [ 1 -eq 1 ]; do netstat -antp | grep 18899 ; sleep 2; echo; done;


image.png

3 测试代码

@Test
public void simpleGet() throws IOException, InterruptedException {
    /**
     * 提交的请求次数
     */
    int index = 1000000;
    while (--index > 0) {
        String target = url /*+ index*/;
        //使用固定20个线程的线程池发起请求
        pool.submit(() -> {
            //使用JDK的 java.net.HttpURLConnection发起HTTP请求
            String out = HttpClientHelper.jdkGet(target);
            System.out.println("out = " + out);
        });
    }
    Thread.sleep(Integer.MAX_VALUE);
}



public static String jdkGet(String url) {
    //输入流
    InputStream inputStream = null;
    //HTTP连接实例
    HttpURLConnection httpConnection = null;
    StringBuilder builder = new StringBuilder();
    try {
        URL restServiceURL = new URL(url);
        //打开HttpURLConnection连接实例
        httpConnection =
                (HttpURLConnection) restServiceURL.openConnection();
        //设置请求头
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Accept", "application/json");
        //建立连接,发送请求
        httpConnection.connect();
        //读取响应
        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP GET Request Failed with Error code : "
                    + httpConnection.getResponseCode());
        }
        //读取响应内容(字节流)
        inputStream = httpConnection.getInputStream();
        byte[] b = new byte[1024];
        int length = -1;
        while ((length = inputStream.read(b)) != -1) {
            builder.append(new String(b, 0, length));
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //关闭流和连接
        quietlyClose(inputStream);
        httpConnection.disconnect();
    }
    return builder.toString();
}