net.Listen
net.Listen是一个Go语言中用于创建网络监听器的函数。它接受一个网络类型和一个地址作为参数,并返回一个实现了net.Listener接口的对象,该对象可以用于接受客户端连接。
下面创建一个TCP服务器监听特定端口,接受客户端连接并返回一个简单的欢迎消息
net.Listen的函数签名如下:
func Listen(network, address string) (Listener, error)
其中,network参数指定了网络类型,可以是"tcp"、"tcp4"、"tcp6"、"unix"或"unixpacket"。address参数指定了监听的网络地址,可以是IP地址和端口号,如"127.0.0.1:8080"。
net.Listen函数返回一个实现了net.Listener接口的对象,我们可以使用该对象进行接受客户端连接。
net.Listener接口定义了以下方法:
Accept():用于接受客户端连接,返回一个实现了net.Conn接口的对象,可以用于与客户端进行通信。Close():用于关闭监听器,停止监听客户端连接。Addr():用于获取监听的网络地址。
type Listener interface {
// Accept waits for and returns the next connection to the listener.
Accept() (Conn, error)
// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors.
Close() error
// Addr returns the listener's network address.
Addr() Addr
}