这就是 TCP 连接主动关闭的工作原理。当客户端检测到服务器已关闭时,预计会关闭其一半的连接。
就您而言,您不是关闭客户端而是发送更多数据。这会导致服务器发送 RST 数据包以强制关闭连接,因为收到的消息无效。
如果您仍然不确定,这里是等效的 python 客户端+服务器,它显示相同的行为。 (我发现使用 python 很有帮助,因为它紧密遵循底层 BSD 套接字 API,而不使用 C)
Server:
import socket, time
server = socket.socket()
server.bind(("127.0.0.1", 9999))
server.listen(1)
sock, addr = server.accept()
msg = sock.recv(1024)
print msg
print "closing"
sock.close()
time.sleep(3)
print "done"
Client:
import socket, time
sock = socket.socket()
sock.connect(("127.0.0.1", 9999))
sock.send("test\n")
time.sleep(1)
print "sending again!"
sock.send("no error here")
time.sleep(1)
print "sending one last time"
sock.send("broken pipe this time")
要正确检测连接上的远程关闭,您应该这样做Read()
,并寻找一个io.EOF
返回错误。
// we technically need to try and read at least one byte,
// or we will get an EOF even if the connection isn't closed.
buff := make([]byte, 1)
if _, err := conn.Read(buff); err != io.EOF {
panic("connection not closed")
}