當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。