2016-06-07 60 views
2

我正在實現一個簡單的代理應用程序,其中我總是從一端接收數據併發送到另一端。TCP關閉()確保所有數據都傳遞給接收器

在這種情況下,一旦我確信我已完成接收來自傳入段的所有數據,我可以直接致電close()而不致致電shutdown()?如果我這樣做,close()將確保所有數據都傳遞到傳出段上的目的地,並由目標應用程序接收?

或者在這種情況下,在我開始關閉之前是否必須啓動關機?

+0

檢查http://stackoverflow.com/questions/8874021/close-socket-directly-after-send-unsafe - 關閉應該使數據傳輸,除非沒有重大的網絡問題。 – coyotte508

回答

0

我可以直接調用close()方法,而不調用shutdown()

可以。 shutdown僅在您想要關閉連接(即讀取或寫入結束)時纔有必要。

將關閉()確保所有數據在目的地

close確實在後臺什麼阻擋send確實傳遞到目的地的呼出支路和接收的應用,不多也不少。如果該背景send失敗,則不會收到任何錯誤指示。

還有SO_LINGER套接字選項你可以調整,如果必要的:

SO_LINGER 
     Sets or gets the SO_LINGER option. The argument is a linger 
     structure. 

      struct linger { 
       int l_onoff; /* linger active */ 
       int l_linger; /* how many seconds to linger for */ 
      }; 

     When enabled, a close(2) or shutdown(2) will not return until 
     all queued messages for the socket have been successfully sent 
     or the linger timeout has been reached. Otherwise, the call 
     returns immediately and the closing is done in the background. 
     When the socket is closed as part of exit(2), it always lingers 
     in the background. 
+1

關於'shutdown()'的小記。它將影響套接字的所有副本,例如用dup(),dup2()或fork()創建的那些套接字。 'close()'函數隻影響套接字的一個副本。如果它沒有關閉最後一個副本,那麼套接字的其他副本將繼續正常運行。 –