I Spy Code - GO

Echo server

Here is an echo server implemented in go lang:

Run the program:
$ go run example.go

In a different terminal run:
$ nc localhost 12345

Source: (example.go)

package main
 
import (
   "fmt"
   "net"
   "bufio"
   "strconv"
)
 
const PORT = 12345
 
func echo(s net.Conn, i int) {
   defer s.Close();
 
   fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
   b := bufio.NewReader(s)
   for {
      line, e := b.ReadBytes('\n')
      if e != nil {
         break
      }
      s.Write(line)
   }
   fmt.Printf("%d: closed\n", i)
}
 
func main() {
   l, e := net.Listen("tcp", ":" + strconv.Itoa(PORT))
   for i := 0; e == nil; i++ {
      var s net.Conn
      s, e = l.Accept()
      go echo(s, i)
   }
}
 

Output:

$ go run example.go &

$ nc localhost 12345

0: [::1]:12345 <-> [::1]:64701
0: closed