golang socket编程 net.Conn IO.EOF解读
结论
首先,先定义下我的理解,当在Read时,收到一个IO.EOF,代表的就是对端已经关闭了发送的通道,通常来说是发起了FIN。
那么根据自己的实际业务,就可以进行判断,这里的IO.EOF到底该怎么利用,比如说判定为作业结束,直接关闭连接,停止业务。或者等待服务端发送完数据再停止业务都是可以的。
GO中IO.EOF的定义
// EOF is the error returned by Read when no more input is available.
// Functions should return EOF only to signal a graceful end of input.
// If the EOF occurs unexpectedly in a structured data stream,
// the appropriate error is either ErrUnexpectedEOF or some other error
// giving more detail.
var EOF = errors.New("EOF")
核心意思就一句,收到这个就代表输入方已经正常结束了。
然后,在看Read方法
// Read implements the Conn Read method.
func (c *conn) Read(b []byte) (int, error) {
if !c.ok() {
return 0, syscall.EINVAL
}
n, err := c.fd.Read(b)
if err != nil && err != io.EOF {
err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
}
return n, err
}
最后的一个if,将io.EOF独立出来了。
分析
首先TCP是全双工的,并且每次关闭的时候,都会发起4次挥手。参考下图
当客户端发起FIN之后,服务器会进如CLOSE_WAIT的状态,这个状态的主要意义在于,如果服务器有没有发送完的数据需要发送给客户端时,那么需要继续发送,当服务器端发送完毕之后,再给客户端回复FIN表示关闭。
所以,咱们可以间接的认为,当我们收到一个IO.EOF的时候,就是客户端在发起FIN了。
首发于:zfcode.com