我正在使用 TcpClient 并调用 Close当我想断开客户端与服务器的连接时。我的理解是,如果尚未调用 Close,则 Close 将调用套接字上的 Shutdown。
谁能解释一下下面上下文中的“终止”是什么意思?根据我的观察,这意味着调用 Shutdown 的一方将发送硬重置 (RST),而不是执行正常的关闭序列(FIN、ACK...)。
来自:https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.shutdown(v=vs.110).aspx
Setting how to Receive specifies that subsequent calls to Receive are not allowed. This has no effect on lower protocol layers. If you are using a connection-oriented protocol, the connection is terminated if either of the following conditions exist after a call to Shutdown :
- Data is in the incoming network buffer waiting to be received.
- More data has arrived.
基于此,如果我想正常关闭,我必须在调用 Close 之前尝试清空本地接收缓冲区。
这是正确的还是有办法保证正常关闭?
最佳答案
通过首先关闭传出 channel socket.Shutdown(SocketShutdown.Send))
并继续读取套接字来完成正常关闭。
另一端会将您的关闭请求读取为 0 字节消息,并且在发送所有剩余数据后,它应该通过关闭其套接字来响应。这会导致您方收到 0 字节消息,从而结束交易。
关于c# - TcpClient 重置与正常关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31975680/