【问题标题】:Does TCP close( ) ensure that all the data is delivered to the receiverTCP close() 是否确保所有数据都传递给接收方
【发布时间】:2016-06-07 17:44:10
【问题描述】:

我正在实现一个简单的代理应用程序,我总是从一端接收数据并发送到另一端。

在这种情况下,一旦我确定我已完成接收来自传入支路的所有数据,我可以直接调用close( ) 而不调用shutdown( ) 吗?如果我这样做,close( ) 是否会确保所有数据都在传出段上传递到目的地并由目的地的应用程序接收?

或者在这种情况下,我是否必须在启动关闭之前启动关闭?

【问题讨论】:

标签: tcp closesocket


【解决方案1】:

我可以直接调用close()而不调用shutdown()

你可以。 shutdown 仅在您想半关闭连接(即读取或写入结束)时才需要。

close() 是否会确保所有数据都在传出分支上传递到目的地并由目的地的应用程序接收

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.

【讨论】:

  • shutdown() 上的小注释。它将影响套接字的所有副本,例如使用dup()dup2()fork() 创建的那些副本。 close() 函数只影响套接字的一个副本。如果它没有关闭最后一个副本,则套接字的其他副本继续正常运行。
猜你喜欢
  • 2012-06-06
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 2021-04-16
  • 2013-06-04
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多