要阅读go的tcp包源码,必须要对tcp协议有一个深入的了解,但这并不在本篇文章讨论范围。
下面是一个简单的用go实现的tcp服务器:
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
os.Exit(1)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
continue
}
fmt.Println("Client connected:", conn.RemoteAddr())
conn.Close()
}
}
先看一看net.Listen函数的注释:
// net/dial.go 837
// Listen announces on the local network address.
//
// The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
//
// For TCP networks, if the host in the address parameter is empty or
// a literal unspecified IP address, Listen listens on all available
// unicast and anycast IP addresses of the local system.
// To only use IPv4, use network "tcp4".
// The address can use a host name, but this is not recommended,
// because it will create a listener for at most one of the host's IP
// addresses.
// If the port in the address parameter is empty or "0", as in
// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
// The [Addr] method of [Listener] can be used to discover the chosen
// port.
//
// See func [Dial] for a description of the network and address
// parameters.
//
// Listen uses context.Background internally; to specify the context, use
// [ListenConfig.Listen].
func Listen(network, address string) (Listener, error) {
var lc ListenConfig
return lc.Listen(context.Background(), network, address)
}