add example with tcp goroutine pool and read only channel
This commit is contained in:
parent
076238e196
commit
2ce705b3ec
49
read-only-chan.go
Normal file
49
read-only-chan.go
Normal file
@ -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<h1>HELLO</h1>\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)
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user