🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## simple dmeo 端口客户端后,服务端协程数不会溢出的版本 <details> <summary>main.go</summary> ``` package main import ( "fmt" "log" "net" ) func main() { tcpAddr, e := net.ResolveTCPAddr("tcp",":5050") if e != nil { log.Panic(e) } tcpListener, e := net.ListenTCP("tcp", tcpAddr) if e != nil { log.Panic(e) } defer tcpListener.Close() for{ tcp, e := tcpListener.AcceptTCP() if e != nil { log.Fatal(e) continue } go handle(tcp) } } func handle(tcp *net.TCPConn) { t := newTcp(tcp) t.Run() } // client type tcp struct { conn *net.TCPConn quit chan struct{} } func newTcp(conn *net.TCPConn) *tcp { return &tcp{ conn: conn, quit:make(chan struct{},1), } } func (t *tcp) Run (){ go t.read() go t.write() } func (t *tcp) read() { a :=make([]byte,1024) for{ n, err := t.conn.Read(a) if err != nil { t.quit <- struct{}{} break } if n == 0 { continue } fmt.Printf("%+v\n", a[:n]) } } func (t *tcp) write() { defer func() { t.conn.Close() }() for{ select { case <-t.quit: return } } } ``` </details> <br/> ``` go run main.go ```