[日常] Go语言圣经-基于select的多路复用习题
2023-02-18 15:41:39 时间
练习 8.8: 使用select来改造8.3节中的echo服务器,为其增加超时,这样服务器可以在客户端10秒中没有任何喊话时自动断开连接。
reverb3.go
package main import ( "bufio" "fmt" "log" "net" "strings" "sync" "time" ) func main() { listener, err := net.Listen("tcp", ":8040") if err != nil { log.Fatal(err) } for { conn, err := listener.Accept() if err != nil { log.Print(err) // e.g., connection aborted continue } go handleConn(conn) //新建goroutines处理连接 } } /* 1.启动一个goroutine,for死循环让他不能断掉 select语句case判断两个channel 一个是10秒后断掉连接 另一个是接收标准输入后发送过来的channel,接收到值后,启动goroutinue输出 2.for循环接收标准输入,接收到后发送给message的channel */ func handleConn(c net.Conn) { input := bufio.NewScanner(c) var wg sync.WaitGroup var message = make(chan string) wg.Add(1) go func() { defer wg.Done() for { select { case <-time.After(10 * time.Second): c.Close() case mes := <-message: wg.Add(1) go func(c net.Conn, shout string, delay time.Duration) { defer wg.Done() fmt.Fprintln(c, "\t", strings.ToUpper(shout)) time.Sleep(delay) fmt.Fprintln(c, "\t", shout) time.Sleep(delay) fmt.Fprintln(c, "\t", strings.ToLower(shout)) //ch<-struct{}{} }(c, mes, 1*time.Second) } } }() for input.Scan() { text := input.Text() message <- text } wg.Wait() //cw := c.(*net.TCPConn) //cw.CloseWrite() c.Close() }
相关文章
- NFS (网络文件系统) | CentOS7 升级系统和内核 | Linux man 命令汉化
- Linux快捷键 | 破解密码 | 正则 | 永久行号显示
- Linux权限管理
- Linux用户账号管理
- Linux逻辑分区| 扩容 | 挂载
- Jgit的使用笔记
- 利用Github Action实现Tornadofx/JavaFx打包
- Linux基础命令
- Linux 基础篇 vim | 网卡
- Linux网络管理 | 三种模式
- Linux打包 | 压缩
- Linux进程管理
- Linux防火墙 | 服务管理
- Linux基础篇
- Linux vim | vi 的使用
- Linux 管理本地用户组 | sudo提权
- Linux培训/考试环境安装 | sudo提权 | cron周期命令
- Linux EX200-RHCSA考题『上篇』
- Linux EX200-RHCSA考题『下篇』
- Linux RHCE环境配置 | 知识点分解讲解