From 2ce705b3ec080ad6824d8851099d11aad47cd0d7 Mon Sep 17 00:00:00 2001 From: Antoine Date: Tue, 8 Dec 2020 23:13:48 +0100 Subject: [PATCH] add example with tcp goroutine pool and read only channel --- read-only-chan.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 read-only-chan.go diff --git a/read-only-chan.go b/read-only-chan.go new file mode 100644 index 0000000..9443657 --- /dev/null +++ b/read-only-chan.go @@ -0,0 +1,49 @@ +package main + +import ( + "fmt" + "log" + "net" +) + +func produce(l *net.TCPListener, c chan<- net.Conn) { + for { + conn, _ := l.Accept() + c <- conn + defer conn.Close() + } +} + +func consume(c <-chan net.Conn) { + fmt.Println("create goroutine consumer") + for conn := range c { + log.Println("someone connected") + var res = make([]byte, 10) + nb, err := conn.Read(res) + if err != nil { + log.Fatalln(err) + } + fmt.Printf("receive %d, contain %s\n", nb, string(res)) + + conn.Write([]byte("HTTP/1.1 200 OK\nContent-Type: text/html; encoding=utf8\nContent-Length: 15\nConnection: close\n\n

HELLO

\n")) + //<-time.After(10 * time.Second) + fmt.Println("Process ended") + } +} + +func main() { + c := make(chan net.Conn, 10) + for i := 0; i < 10; i++ { + go consume(c) + } + + addr := net.TCPAddr{ + IP: net.ParseIP("127.0.0.1"), + Port: 3000, + } + l, err := net.ListenTCP("tcp", &addr) + if err != nil { + log.Fatalln(err) + } + produce(l, c) +}