3
如果UDP是无连接协议,那么为什么UDPConn
有一个Close
方法?该文档称“关闭关闭连接”,但UDP是无连接的。在UDPConn
对象上调用Close
是否是好习惯?有什么好处吗?UDPConn Close真的做了什么?
http://golang.org/pkg/net/#UDPConn.Close
如果UDP是无连接协议,那么为什么UDPConn
有一个Close
方法?该文档称“关闭关闭连接”,但UDP是无连接的。在UDPConn
对象上调用Close
是否是好习惯?有什么好处吗?UDPConn Close真的做了什么?
http://golang.org/pkg/net/#UDPConn.Close
好问题,让我们看到的udpconn.Close
http://golang.org/src/pkg/net/net.go?s=3725:3753#L124
func (c *conn) Close() error {
if !c.ok() {
return syscall.EINVAL
}
return c.fd.Close()
}
代码关闭c.fd
但什么是c.fd?
type conn struct {
fd *netFD
}
ok是一个netFD
网络文件描述符。我们来看看Close
方法。
func (fd *netFD) Close() error {
fd.pd.Lock() // needed for both fd.incref(true) and pollDesc.Evict
if !fd.fdmu.IncrefAndClose() {
fd.pd.Unlock()
return errClosing
}
// Unblock any I/O. Once it all unblocks and returns,
// so that it cannot be referring to fd.sysfd anymore,
// the final decref will close fd.sysfd. This should happen
// fairly quickly, since all the I/O is non-blocking, and any
// attempts to block in the pollDesc will return errClosing.
doWakeup := fd.pd.Evict()
fd.pd.Unlock()
fd.decref()
if doWakeup {
fd.pd.Wakeup()
}
return nil
}
通知所有decref
因此,要回答你的问题。是。是好的做法,否则你会留在内存网络文件描述符中。