Andrew Gerrand | 3e804f9 | 2012-02-18 11:48:33 +1100 | [diff] [blame] | 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 | } |
Mikio Hara | 66b797a | 2013-03-29 15:07:10 +0900 | [diff] [blame] | 19 | defer l.Close() |
Andrew Gerrand | 3e804f9 | 2012-02-18 11:48:33 +1100 | [diff] [blame] | 20 | for { |
Robert Griesemer | 465b9c3 | 2012-10-30 13:38:01 -0700 | [diff] [blame] | 21 | // Wait for a connection. |
Andrew Gerrand | 3e804f9 | 2012-02-18 11:48:33 +1100 | [diff] [blame] | 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 | } |