2 回答
TA贡献2051条经验 获得超10个赞
我可以通过在关闭连接之前使用es.done发送信号来处理此问题。除了以下代码,您还需要使用make(chan bool,1)创建es.done,以便我们可以在其中添加单个值而不会阻塞。
// Listen for incoming connections
func (es *EchoServer) serve() {
for {
conn, err := es.listen.Accept()
if err != nil {
select {
case <-es.done:
// If we called stop() then there will be a value in es.done, so
// we'll get here and we can exit without showing the error.
default:
log.Printf("Accept failed: %v", err)
}
return
}
go es.respond(conn.(*net.TCPConn))
}
}
// Stop the server by closing the listening listen
func (es *EchoServer) stop() {
es.done <- true // We can advance past this because we gave it buffer of 1
es.listen.Close() // Now it the Accept will have an error above
}
- 2 回答
- 0 关注
- 275 浏览
添加回答
举报