golang chan的运用

今天看gopl看到书上的例子看的不太懂,不是搞开发的,上了岁数理解能力也差,仔细的分析分析

package main


import (
"bufio"
"fmt"
"log"
"net"
)


type client chan<- string


var (

        //管道的管道
entering = make(chan client)
leaving  = make(chan client)
messages = make(chan string)
)


func main() {
listener, err := net.Listen("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatal(err)
}
go boadcaster()
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go handlerconn(conn)
}
}


func boadcaster() {

        //限制在函数内,并发安全
clients := make(map[client]bool)
for {
select {
case msg := <-messages:
for cli := range clients { //发送给所有在线客户端,交给对应的clientwriter
cli <- msg
}
case cli := <-entering:
clients[cli] = true //添加进map
case cli := <-leaving:
delete(clients, cli) //注销连接
close(cli)           //显式关闭管道
}
}
}
func handlerconn(conn net.Conn) {
ch := make(chan string)
go clientwriter(conn, ch) //向对应客户端写入数据
who := conn.RemoteAddr().String()
ch <- "you are: " + who          //直接输出到对应客户端
messages <- who + " has arrived" //输出到所有客户端
entering <- ch                   //注册chan
input := bufio.NewScanner(conn)  //遍历客户端输入
for input.Scan() {
messages <- who + ": " + input.Text() //输出给所有人
}
leaving <- ch                //发送关闭信号
messages <- who + "has left" //输出给所有人
conn.Close()
}


func clientwriter(conn net.Conn, ch chan string) {
for msg := range ch {
fmt.Fprintln(conn, msg)
}
}

你可能感兴趣的:(golang)