如何中断执行 (*TCPListener) Accept 的 goroutine?

我最近在玩 go 并尝试制作一些服务器来响应 tcp 连接上的客户端。

我的问题是如何干净地关闭服务器并中断当前在以下调用中“阻塞”的 go-routine

func (*TCPListener) 接受吗?

根据Accept文档

Accept在Listener接口中实现了Accept方法;它等待下一次调用并返回一个通用的 Conn。

这些错误也几乎没有记录。


慕仙森
浏览 286回答 3
3回答

侃侃无极

TCP侦听器截止日期您不一定需要额外的 go 例程(不断接受),只需指定一个Deadline.for 例子:for {&nbsp; &nbsp; // Check if someone wants to interrupt accepting&nbsp; &nbsp; select {&nbsp; &nbsp; case <- someoneWantsToEndMe:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return // runs into "defer listener.Close()"&nbsp; &nbsp; default: // nothing to do&nbsp; &nbsp; }&nbsp; &nbsp; // Accept with Deadline&nbsp; &nbsp; listener.SetDeadline(time.Now().Add(1 * time.Second)&nbsp; &nbsp; conn, err := listener.Accept()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // TODO: Could do some err checking (to be sure it is a timeout), but for brevity&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; }&nbsp; &nbsp; go handleConnection(conn)}

白猪掌柜的

只需Close()将net.Listener你从一开始net.Listen(...)呼叫,从正在执行的够程返回。

阿波罗的战车

这就是我要找的。也许将来会帮助某人。注意使用 select 和 "c" 通道将它与退出通道结合起来&nbsp; &nbsp; ln, err := net.Listen("tcp", ":8080")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; }&nbsp; &nbsp; defer ln.Close()&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; type accepted struct {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; conn net.Conn&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; err&nbsp; error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; c := make(chan accepted, 1)&nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; conn, err := ln.Accept()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c <- accepted{conn, err}&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case a := <-c:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if a.err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go handleConnection(a.conn)&nbsp; &nbsp; &nbsp; &nbsp; case e := <-ev:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // handle event&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go