3 回答
TA贡献2051条经验 获得超10个赞
TCP侦听器截止日期
您不一定需要额外的 go 例程(不断接受),只需指定一个Deadline.
for 例子:
for {
// Check if someone wants to interrupt accepting
select {
case <- someoneWantsToEndMe:
return // runs into "defer listener.Close()"
default: // nothing to do
}
// Accept with Deadline
listener.SetDeadline(time.Now().Add(1 * time.Second)
conn, err := listener.Accept()
if err != nil {
// TODO: Could do some err checking (to be sure it is a timeout), but for brevity
continue
}
go handleConnection(conn)
}
TA贡献1862条经验 获得超6个赞
这就是我要找的。也许将来会帮助某人。注意使用 select 和 "c" 通道将它与退出通道结合起来
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
}
defer ln.Close()
for {
type accepted struct {
conn net.Conn
err error
}
c := make(chan accepted, 1)
go func() {
conn, err := ln.Accept()
c <- accepted{conn, err}
}()
select {
case a := <-c:
if a.err != nil {
// handle error
continue
}
go handleConnection(a.conn)
case e := <-ev:
// handle event
return
}
}
- 3 回答
- 0 关注
- 278 浏览
添加回答
举报