Created
April 5, 2017 18:02
-
-
Save jordanorelli/35a9077d515cd309a6ff38fed2fa21e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net" | |
"os" | |
"os/signal" | |
"time" | |
) | |
var ( | |
info_log = log.New(os.Stdout, "i ", log.LstdFlags) | |
error_log = log.New(os.Stderr, "e ", log.LstdFlags) | |
) | |
func bail(status int, t string, args ...interface{}) { | |
if status == 0 { | |
info_log.Printf(t, args...) | |
} else { | |
error_log.Printf(t, args...) | |
} | |
os.Exit(0) | |
} | |
var opts struct { | |
port int | |
} | |
func handle(conn net.Conn) { | |
for count := 0; count < 10000; count++ { | |
fmt.Fprintln(conn, "hi. count: ", count) | |
time.Sleep(1 * time.Second) | |
} | |
} | |
func main() { | |
flag.IntVar(&opts.port, "port", 9000, "the port on which we listen") | |
flag.Parse() | |
l, err := net.ListenTCP("tcp4", &net.TCPAddr{Port: opts.port}) | |
if err != nil { | |
bail(1, "couldn't open port %d: %v", opts.port, err) | |
} | |
c := make(chan os.Signal, 1) | |
signal.Notify(c, os.Interrupt, os.Kill) | |
go func() { | |
<-c | |
info_log.Printf("closing listener") | |
l.Close() | |
}() | |
for { | |
conn, err := l.Accept() | |
if err != nil { | |
error_log.Printf("unable to accept new connection: %v", err) | |
break | |
} | |
go handle(conn) | |
} | |
<-c | |
bail(0, "shutting down") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment