網絡通信系列文章序
徹底掌握網絡通信(一)Http協議基礎知識
徹底掌握網絡通信(二)Apache的HttpClient基礎知識
徹底掌握網絡通信(三)Android源碼中HttpClient的在不同版本的使用
徹底掌握網絡通信(四)Android源碼中HttpClient的發送框架解析
徹底掌握網絡通信(五)DefaultRequestDirector解析
徹底掌握網絡通信(六)HttpRequestRetryHandler解析
徹底掌握網絡通信(七)ConnectionReuseStrategy,ConnectionKeepAliveStrategy解析
徹底掌握網絡通信(八)AsyncHttpClient源碼解讀
徹底掌握網絡通信(九)AsyncHttpClient為什么無法用Fiddler來抓包
徹底掌握網絡通信(十)AsyncHttpClient如何發送JSON解析JSON,以及一些其他用法
前面簡單說了下HttpRequestRetryHandler,這篇主要分析下ConnectionReuseStrategy,ConnectionKeepAliveStrategy,連接的重用和長連接
1:基礎介紹
1.1)Keep-Alive解析
http協議作為上層應用層協議,其是基於TCP/IP協議,UDP協議傳輸層上進行的;http協議通過socket這個套接字完成客戶端和服務端的通信;
http協議目前主要有兩個版本HTTP 1.0和HTTP 1.1,他們都是無狀態協議
在HTTP 1.0中,每一次請求響應之后,下一次的請求需要斷開之前的連接,再重新開始;
在HTTP 1.1中,使用keep-alive在一次TCP連接中可以持續發送多份數據而不會斷開連接。通過使用keep-alive機制,可以減少tcp連接建立次數,也意味着可以減少TIME_WAIT狀態連接,以此提高性能和提高httpd服務器的吞吐率(更少的tcp連接意味着更少的系統內核調用,socket的accept()和close()調用)。
因此便出現了Connection: keep-alive的設置,用於建立長連接,即我們所說的Keep-Alive模式;
如上圖,左圖是HTTP 1.0 ; 右圖是HTTP 1.1
http 1.0中默認是關閉的,需要在http頭加入”Connection: Keep-Alive”,才能啟用Keep-Alive;
在1.0中,如果客戶端瀏覽器支持Keep-Alive,那么就在HTTP請求頭中添加一個字段 Connection: Keep-Alive,當服務器收到附帶有Connection: Keep-Alive的請求時,它也會在響應頭中添加一個同樣的字段來使用Keep-Alive。這樣一來,客戶端和服務器之間的HTTP連接就會被保持,不會斷開(超過Keep-Alive規定的時間,意外斷電等情況除外),當客戶端發送另外一個請求時,就使用這條已經建立的連接
http 1.1中默認啟用Keep-Alive,如果加入”Connection: close “,才關閉。
Keep-Alive不會永久保持連接,它有一個保持時間,可以在不同的服務器軟件(如Apache)中設定這個時間;
一次完成的http請求是否能夠保持,同時也要靠服務端是否具備Keep-Alive能力;
1.2)如何判斷客戶端已經完整的接收到服務端的數據,針對HTTP 1.0和HTTP 1.1
在java中,使用socket編程的時候,我們經常看到如下代碼
Socket socket = new Socket("localhost",10086);
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = null;
while((info=br.readLine()) != -1){
}
1
2
3
4
5
6
7
所以在普通的socket編程中,我們可以使用EOF(-1)來判斷是否完整的接收到服務端的返回的數據;這是因為在一次普通的http請求中,即沒有添加Connection: Keep-Alive屬性的http請求中,服務端響應之后,會斷開連接,顧使用EOF判斷是准確的;
但是這種方式針對添加Connection: Keep-Alive屬性的http請求來說,就無法生效了;
我們可以通過頭消息中的Conent-Length字段來判斷;但是對於動態頁面或者zip格式的內容,服務端一般會采用Transfer-Encoding: chunked”這樣的方式來代替Content-Length;
因此
在Http 1.0及之前版本中,content-length字段可有可無。
在http1.1及之后版本。如果是keep alive,則content-length和chunk必然是二選一。若是非keep alive,則和http1.0一樣。content-length可有可無。
2:在DefaultRequestDirector.execute方法中有如下代碼
// The connection is in or can be brought to a re-usable state.
reuse = reuseStrategy.keepAlive(response, context);
if(reuse) {
// Set the idle duration of this connection
long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
}
1
2
3
4
5
6
7
從這段代碼可以看出,當完成一次http請求之后,並沒有立即關閉這個tcp連接和釋放資源;而是通過可重用策略來判斷這個連接能否被保持,以及保持多長時間;
我們先分析下如何判斷這個連接是否是可重用的,我們可以通過上面的keepAlive方法來進行具體分析,reuseStrategy的默認實現者為DefaultConnectionReuseStrategy,我們看一下keepAlive方法
//該方法的作用就是在一次請求之后,這個連接能夠被保持
//如果返回false,則調用者應該立即關閉連接
//如果返回true,則調用者應該保持這個連接從而可以應用於其他請求
public boolean keepAlive(final HttpResponse response,
final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException
("HTTP response may not be null.");
}
if (context == null) {
throw new IllegalArgumentException
("HTTP context may not be null.");
}
HttpConnection conn = (HttpConnection)
context.getAttribute(ExecutionContext.HTTP_CONNECTION);
//當一個連接沒有建立的時候,當然是不可重用的,返回false
if (conn != null && !conn.isOpen())
return false;
// do NOT check for stale connection, that is an expensive operation
// Check for a self-terminating entity. If the end of the entity will
// be indicated by closing the connection, there is no keep-alive.
HttpEntity entity = response.getEntity();
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
//當返回的entity的長度小於0,並且http協議版本號小於1.0,返回false
if (entity != null) {
if (entity.getContentLength() < 0) {
if (!entity.isChunked() ||
ver.lessEquals(HttpVersion.HTTP_1_0)) {
// if the content length is not known and is not chunk
// encoded, the connection cannot be reused
return false;
}
}
}
// Check for the "Connection" header. If that is absent, check for
// the "Proxy-Connection" header. The latter is an unspecified and
// broken but unfortunately common extension of HTTP.
//HTTP.CONN_DIRECTIVE的值為Connection,即獲取響應頭信息中的Connection字段的內容
HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
//如果沒有這個頭信息,則尋找Proxy-Connection的頭信息
if (!hit.hasNext()){
//Proxy-Connection是http1.0 時代的產物。老舊的代理,如果設置 connection: keepalive,
//代理原樣轉發給服務器,服務器會以為要建立長久連接,但是代理並不支持,這樣就出問題了。
//所以改為設置 proxy-connection: keepalive,如果是新的代理,
//支持 keepalive,它會認得這個頭,並改成 connection: keepalive 轉發給服務器,
//順利建立持久連接;如果是老的代理,它不認識,會原樣轉發,這時候服務器也不會建立持久連接
hit = response.headerIterator("Proxy-Connection");
}
if (hit.hasNext()) {
try {
TokenIterator ti = createTokenIterator(hit);
boolean keepalive = false;
while (ti.hasNext()) {
final String token = ti.nextToken();
//如果Connection:close則返回false
if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
return false;
}//如果Connection:Keep-Alive則返回true
else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
// continue the loop, there may be a "close" afterwards
keepalive = true;
}
}
if (keepalive)
return true;
// neither "close" nor "keep-alive", use default policy
} catch (ParseException px) {
// invalid connection header means no persistent connection
// we don't have logging in HttpCore, so the exception is lost
return false;
}
}
// default since HTTP/1.1 is persistent, before it was non-persistent
return !ver.lessEquals(HttpVersion.HTTP_1_0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
總結
1:該方法的作用就是在一次請求之后,這個連接能否被保持,如果返回false,則調用者應該立即關閉連接;如果返回true,則調用者應該保持這個連接從而可以應用於其他請求
2:由於HTTP 1.0時代,還不能有效支持connection,顧多了一個Proxy-Connection頭信息,該字段的出現的原因是: 在HTTP 1.0中老舊的代理,如果設置 connection: keepalive,代理原樣轉發給服務器,服務器會以為要建立長久連接,但是代理並不支持,這樣就出問題了。所以改為設置 proxy-connection: keepalive,如果是新的代理,支持 keepalive,它會認得這個頭,並改成 connection: keepalive 轉發給服務器,順利建立持久連接;如果是老的代理,它不認識,會原樣轉發,這時候服務器也不會建立持久連接
當一個請求視為可重用之后,即keepAlive返回true,那這么鏈接能一直保持鏈接狀態?會不會超過一定時間,連接就斷開?
答案是會的,當鏈接超過預設時間,會自動斷開;
當一個鏈接是可重用的,我們就可以通過如下代碼獲得這個鏈接可以存活的時間
keepAliveStrategy.getKeepAliveDuration
1
keepAliveStrategy的實現為DefaultConnectionKeepAliveStrategy
public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
HeaderElementIterator it = new BasicHeaderElementIterator(
//HTTP.CONN_KEEP_ALIVE的為“Keep-Alive”
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(NumberFormatException ignore) {
}
}
}
return -1;
}
}
代碼很簡單,就是通過Keep-Alive頭信息中,獲得timeout的值,作為超時時間;單位毫秒;
如請求頭中 Keep-Alive: timeout=5, max=100
---------------------
作者:yi_master
來源:CSDN
原文:https://blog.csdn.net/yi_master/article/details/80595372
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!