Created
February 16, 2016 20:46
-
-
Save hartfordfive/6671dbf9c3518e319402 to your computer and use it in GitHub Desktop.
Simple Go TCP server with asynchronous writing to log file
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 | |
| // 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