This is a creation in Article, where the information may have evolved or changed.
Programming interface
Internal data structure
Listener and TcpListener
In simple terms, one is an interface, and the other is a concrete implementation. Because Golang support TCP, UDP and other protocols, natural use of Golang interface.
Listener defines the various interfaces for the socket operation:
type Listener interface { Accept() (c Conn, err error) Close() error Addr() Addr }
TcpListener defines the data structure that the TCP protocol needs to use
type TCPListener struct { fd *netFD}
NETFD is the core data structure of the Golang network library, which runs through all the APIs of the Golang Network library, encapsulates the underlying sockets and shields the network implementations of different OSes. We will then analyze the data structure separately. The FD in TcpListener is the socket associated with the listening socket.
Conn and Tcpconn
The relationship between Conn and Tcpconn is similar to listener and TcpListener. is also the relationship between abstraction and figurative.
type TCPConn struct { conn}type conn struct { fd *netFD}
Netfd
This structure is too critical to say that it is the core data structure of the Golang network library is not too much. All Golang network interfaces will eventually be transformed into methods for that structure.
// Network file descriptor. type netFD struct { // 不太明白这个mutex的作用 fdmu fdMutex // 该socket相关的fd sysfd int family int sotype int isConnected bool net string laddr Addr raddr Addr // wait server // 与epoll相关结构 pd pollDesc}
And the most important one in this structure is the last member. Pd,golang Network library achieves high concurrency and relies on it all.
type pollDesc struct { runtimeCtx uintptr}
Roughly combing the basic data structures in the Golang network library, we can then go deep into the internal implementation process.