Skip to content

Instantly share code, notes, and snippets.

@hartfordfive
Created February 16, 2016 20:46
Show Gist options
  • Select an option

  • Save hartfordfive/6671dbf9c3518e319402 to your computer and use it in GitHub Desktop.

Select an option

Save hartfordfive/6671dbf9c3518e319402 to your computer and use it in GitHub Desktop.
Simple Go TCP server with asynchronous writing to log file
package main
// Source: http://divan.github.io/posts/go_concurrency_visualize/
import (
"fmt"
"net"
"time"
)
func handler(c net.Conn, ch chan string) {
ch <- c.RemoteAddr().String()
c.Write([]byte("ok"))
c.Close()
}
func logger(ch chan string) {
for {
fmt.Println(<-ch)
}
}
func server(l net.Listener, ch chan string) {
for {
c, err := l.Accept()
if err != nil {
continue
}
go handler(c, ch)
}
}
func main() {
l, err := net.Listen("tcp", ":5000")
if err != nil {
panic(err)
}
ch := make(chan string)
go logger(ch)
go server(l, ch)
time.Sleep(10 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment