当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Listener用法及代码示例


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)
	}
}

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Listener。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。