GO语言"net"包中"Listener"类型的用法及代码示例。
侦听器是stream-oriented 协议的通用网络侦听器。
多个 goroutine 可以同时调用 Listener 上的方法。
用法:
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
}
例子:
package main
import (
"io"
"log"
"net"
)
func main() {
// Listen on TCP port 2000 on all available unicast and
// anycast IP addresses of the local system.
l, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// Wait for a connection.
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// Handle the connection in a new goroutine.
// The loop then returns to accepting, so that
// multiple connections may be served concurrently.
go func(c net.Conn) {
// Echo all incoming data.
io.Copy(c, c)
// Shut down the connection.
c.Close()
}(conn)
}
}
相关用法
- GO ListenAndServe用法及代码示例
- GO ListenAndServeTLS用法及代码示例
- GO LimitReader用法及代码示例
- GO LeadingZeros32用法及代码示例
- GO Logger.Output用法及代码示例
- GO LastIndex用法及代码示例
- GO Log10用法及代码示例
- GO Log用法及代码示例
- GO LeadingZeros8用法及代码示例
- GO LeadingZeros16用法及代码示例
- GO LastIndexAny用法及代码示例
- GO Logger用法及代码示例
- GO Len8用法及代码示例
- GO LoadLocation用法及代码示例
- GO LastIndexFunc用法及代码示例
- GO Len64用法及代码示例
- GO LoadX509KeyPair用法及代码示例
- GO LookPath用法及代码示例
- GO LookupEnv用法及代码示例
- GO Len32用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Listener。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。