填坑系列——TCP/IP中的Nagle算法

問題:

          寫交易所模擬網關發送工具時,測得快照全鏈路時間200多微,逐筆80多微。時間異常的大,通過查找分析發現TCP默認開啓Nagle算法,未設置TCP_NODELAY將緩存等待的時間計算進去導致時間過大。

分析:

TCP/IP協議中針對TCP默認開啓了Nagle算法。Nagle算法通過減少需要傳輸的數據包,提高網絡的利用率,來優化網絡。對於延時敏感型同時數據傳輸量較小的應用可以開啓TCP_NODELAY選項。開啓Nagle算法,數據緩存到一定量後,纔會發送出去,這樣不可避免的增加了延遲。與TCP Delayed ACK延遲確認機制(1、有響應數據時,ACK附帶響應數據一起發送給對方2、沒有響應數據,等待一個延遲 Delay Time後發送)特性結合,延遲會更加顯著,基本在40ms左右。這個現象只會在進行連續兩次寫操作時候體現。

摘自Wikipedia的Nagle算法的僞碼實現:

if there is new data to send
  if the window size >= MSS and available data is >= MSS
    send complete MSS segment now
  else
    if there is unconfirmed data still in the pipe
      enqueue data in the buffer until an acknowledge is received
    else
      send data immediately
    end if
  end if
end if

通過這段僞代碼,發現對於讀-寫-讀-寫模式,關閉TCP_NODELAY問題不大。連續多次小數據包寫操作,然後讀,應該在應用層進行優化。

參考文獻:

https://www.zhihu.com/question/42308970

https://blog.csdn.net/asklw/article/details/79246959

https://blog.csdn.net/historyasamirror/article/details/6423235

https://blog.csdn.net/historyasamirror/article/details/6122284

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章