2013-10-05 224 views
1

我正在用.NET編寫一個簡單的HTTP客戶端用於學習目的。我正在使用.NET Socket類,它最終使用Winsock。我不想使用WebRequest,HttpWebRequestHttpClient類,因爲它們使用WinINet,我不想使用它,因爲我爲了自己理解HTTP的工作原理而使用它。HTTP響應何時完成?

我想知道如何確定HTTP響應何時完成。通過閱讀HTTP/1.1規範(RFC 2616),我認爲以下僞代碼是如何確定HTTP響應何時完成的。

parse HTTP headers 
if parse not successful: 
    throw error 
if HTTP version is 1.1 and Transfer-encoding is chunked: 
    parse first line of each chunk as an ASCII hexadecimal, the chunk size 
    if parse not successful: 
     throw error 
    read each chunk until chunk size 0 
else if Content-Length is specified: 
    read Content-Length number of bytes 
else: 
    throw error 

這是一個或多或少正確的方法?

+0

[HTTP響應結束](可能重複http://stackoverflow.com/questions/17515565/end-of -an-http-response) – CodeCaster

+1

請參閱RFC 2616第4.4節(http://tools.ietf.org/html/rfc2616#section-4.4)以瞭解更多案例。 – cubetwo1729

回答

0

你的理解是大多正確的,有一些小的校正,每RFC 2616 Section 4.4

Read and parse HTTP headers 
if not successful: 
    throw error 
if response can contain message body: 
    if HTTP version is 1.1+ and Transfer-encoding is not identity: 
     while true: 
      read line, extract delimited ASCII hexadecimal, the chunk size 
      if not successful: 
       throw error 
      if chunk size is 0: 
       break while loop 
      read chunk size number of bytes 
     read and parse trailing HTTP headers 
    else if Content-Length is specified: 
     read Content-Length number of bytes 
    else if Content-Type is "multipart/byteranges": 
     read and parse MIME-encoded chunks until terminating MIME boundary is reached 
    else: 
     read until connection is closed