Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created July 19, 2012 22:14
Show Gist options
  • Save jordanorelli/3147239 to your computer and use it in GitHub Desktop.
Save jordanorelli/3147239 to your computer and use it in GitHub Desktop.
tcp echo server in Go
package main
import (
"bufio"
"fmt"
"net"
"os"
)
var incoming_port = "0.0.0.0:9001"
func echo(conn net.Conn) {
r := bufio.NewReader(conn)
for {
line, err := r.ReadBytes(byte('\n'))
if err != nil {
fmt.Println("ERROR", err)
break
}
conn.Write(line)
}
}
func main() {
l, err := net.Listen("tcp", incoming_port)
if err != nil {
fmt.Println("ERROR", err)
os.Exit(1)
}
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("ERROR", err)
continue
}
go echo(conn)
}
}
@jordanorelli
Copy link
Author

line 16 will catch EOF and call it an error, but this isn't really supposed to be robust or anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment