首页 > 编程知识 正文

HTTP长连接设置

时间:2023-05-05 22:02:58 阅读:273134 作者:394

1. HTTP长连接是指在一个TCP长连接中发送和接收多个HTTP报文。
相应地,短连接则指发送一个HTTP请求后直接关闭TCP连接。
HTTP1.0默认使用短连接,可以在客户端HTTP报文头部添加Connection:Keep-alive启用长连接请求。
HTTP1.1默认使用长连接,可以在客户端HTTP报文头部添加Connection:Closed关闭长连接请求。
HTTP1.1的请求报文和响应报文可以没有Connection:Keep-alive报头,但仍然是长连接。

2. HTTP客户端设置
以基于commons-httpclient-3.0.jar为例

/********HTTP1.1显式关闭长连接**********/
Integer TIME_OUT = 5 * 1000;
String postUrl = http://10.1.1.12:8080/postData
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIME_OUT);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIME_OUT);
InputStream input = new ByteArrayInputStream(postData.getBytes("UTF-8"));
RequestEntity entity = new InputStreamRequestEntity(input);
PostMethod post = new PostMethod(postUrl);
// 选择HTTP协议版本HTTP1.1
post.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// 显式关闭长连接
post.setRequestHeader("Connection", "Closed");
post.setRequestEntity(entity);
try {
    // 发送POST请求
    httpClient.executeMethod(post);
    String retCharSet = post.getResponseCharSet();
    StatusLine statusLine = post.getStatusLine();
    Integer statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        returnStr = new String(post.getResponseBodyAsString().getBytes(retCharSet), retCharSet);
        System.out.println("post响应: " + returnStr);
        System.out.println("post耗时: " + (System.currentTimeMillis() - startTime) + "(ms)");
    }
} finally {
    post.releaseConnection();
}
/********HTTP1.1显式关闭长连接**********/

3. HTTP服务端设置
以免安装版Tomcat7为例
(1) 在conf/server.xml中设置keepAliveTimeout,表示多少毫秒后如果客户端没有新的请求则关闭当前连接。
<Connector acceptCount="1000" keepAliveTimeout="5000" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
keepAliveTimeout默认与connectionTimeout一致。

(2) 在conf/server.xml中设置maxKeepAliveRequests,表示一个长连接最多接收多少个请求,设置为1则为关闭长连接,设置为-1表示无限制。
<Connector acceptCount="1000" maxKeepAliveRequests="1" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。

  •  标签:  
  • HTTP