Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple echo server testing a few interesting Go language features, goroutines and channels.
// $ 6g echo.go && 6l -o echo echo.6
// $ ./echo
//
// ~ in another terminal ~
//
// $ nc localhost 3540
package main
import (
"net"
"bufio"
"strconv"
"fmt"
)
const PORT = 3540
func main() {
server, err := net.Listen("tcp", ":" + strconv.Itoa(PORT))
if server == nil {
panic("couldn't start listening: " + err.String())
}
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.String())
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
}
client.Write(line)
}
}

this is good stuff

Opa- commented Jun 8, 2015

Wow, thanks man !

Cool Thanks

thank you so much!

lonnietc commented Sep 23, 2016 edited

Solved it... Thanks

barryz commented Oct 23, 2016 edited

why use a unbuffered channel ?

yerden commented Feb 19, 2017 edited

one can just do simple copy if there's no need to check for new line:

import "io"
...
func handleConn(client net.Conn) {
   io.Copy(client, client);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment