github.com/razvanm/vanadium-go-1.3@v0.0.0-20160721203343-4a65068e5915/src/net/example_test.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package net_test
     6  
     7  import (
     8  	"io"
     9  	"log"
    10  	"net"
    11  )
    12  
    13  func ExampleListener() {
    14  	// Listen on TCP port 2000 on all interfaces.
    15  	l, err := net.Listen("tcp", ":2000")
    16  	if err != nil {
    17  		log.Fatal(err)
    18  	}
    19  	defer l.Close()
    20  	for {
    21  		// Wait for a connection.
    22  		conn, err := l.Accept()
    23  		if err != nil {
    24  			log.Fatal(err)
    25  		}
    26  		// Handle the connection in a new goroutine.
    27  		// The loop then returns to accepting, so that
    28  		// multiple connections may be served concurrently.
    29  		go func(c net.Conn) {
    30  			// Echo all incoming data.
    31  			io.Copy(c, c)
    32  			// Shut down the connection.
    33  			c.Close()
    34  		}(conn)
    35  	}
    36  }