// conn 包示例:带流量统计/限速的连接包装(读写自动计入 flow/rate,Close 幂等) package main import ( "fmt" "io" "net" "sync" "git.zeroonesoft.cn/golib/zogo/conn" "git.zeroonesoft.cn/golib/zogo/flow" "git.zeroonesoft.cn/golib/zogo/rate" ) func main() { // 本地 echo 服务 l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } go func() { for { c, err := l.Accept() if err != nil { return } go func() { io.Copy(c, c) c.Close() }() } }() raw, err := net.Dial("tcp", l.Addr().String()) if err != nil { panic(err) } // rate.NewRate(0) 表示不限速;限速时传入 Mbps 并调用 Start() r := rate.NewRate(0) f := &flow.Flow{} wg := &sync.WaitGroup{} wg.Add(1) // 用 conn.Conn 包装原始连接 c := conn.NewConn(raw, r, f, wg) c.Write([]byte("hello go-hua")) buf := make([]byte, 12) n, _ := c.Read(buf) fmt.Println("echo:", string(buf[:n])) // 读写流量自动统计 send, recv := f.Get() fmt.Printf("连接累计流量: 写入 %d 字节, 读取 %d 字节\n", send, recv) // Close 只会真正关闭一次,并触发 wg.Done c.Close() wg.Wait() fmt.Println("连接已关闭") }