package main import ( "flag" "fmt" "io" "net" "os" "strconv" ) func usage() { fmt.Fprintf(os.Stderr, "\nusage: go run chatserver.go\n") flag.PrintDefaults(); fmt.Println() os.Exit(1) } func handleConnection(conn net.Conn) { // Why don't these work? //buf := make([]byte, 0, 1024) //buf := []byte{} // But this does buf := make([]byte, 1024) for { count, err := conn.Read(buf) if nil != err { if io.EOF != err { fmt.Fprintf(os.Stderr, "Non-EOF socket error: %s\n", err) } fmt.Fprintf(os.Stdout, "Ending socket\n") break } // not so sure about why this case exists // we'll just ignore it for now... if 0 == count { // fmt.Fprintf(os.Stdout, "Weird") continue } fmt.Fprintf(os.Stdout, "Message:\n%s\n", buf[0:count]) } } func main() { flag.Usage = usage port:= flag.Uint("telnet-port", 4080, "tcp telnet chat port") flag.Parse() addr := ":" + strconv.Itoa(int(*port)) // https://golang.org/pkg/net/ sock, err := net.Listen("tcp", addr) if nil != err { fmt.Fprintf(os.Stderr, "Couldn't bind to TCP socket %q: %s\n", addr, err) os.Exit(2) } fmt.Println("Listening on", addr); for { conn, err := sock.Accept() if err != nil { // Not sure what kind of error this could be or how it could happen. // Could a connection abort or end before it's handled? fmt.Fprintf(os.Stderr, "Error accepting connection:\n%s\n", err) } fmt.Fprintf(os.Stdout, "Accepting socket\n") go handleConnection(conn) } }