Skip to content

Instantly share code, notes, and snippets.

@garsue
Forked from paulsmith/echo.go
Last active October 12, 2016 08:30
Show Gist options
  • Save garsue/51028b0021fa05708add589421c2ba17 to your computer and use it in GitHub Desktop.
Save garsue/51028b0021fa05708add589421c2ba17 to your computer and use it in GitHub Desktop.
A simple echo server testing a few interesting Go language features, goroutines and channels.
package main
import (
"bufio"
"fmt"
"net"
"strconv"
)
const port = 3540
func main() {
server, err := net.Listen("tcp", ":"+strconv.Itoa(port))
if server == nil {
panic("couldn't start listening: " + err.Error())
}
conns := clientConns(server)
for {
go handleConn(<-conns)
}
}
func clientConns(listener net.Listener) chan net.Conn {
ch := make(chan net.Conn)
i := 0
go func() {
for {
client, err := listener.Accept()
if client == nil {
fmt.Printf("couldn't accept: " + err.Error())
continue
}
i++
fmt.Printf("%d: %v <-> %v\n", i, client.LocalAddr(), client.RemoteAddr())
ch <- client
}
}()
return ch
}
func handleConn(client net.Conn) {
b := bufio.NewReader(client)
for {
line, err := b.ReadBytes('\n')
if err != nil { // EOF, or worse
break
}
fmt.Print(string(line))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment