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

问题描述:

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

I am playing with go lately and trying to make some server which responds to clients on a tcp connection.

我的问题是我该如何干净地关闭服务器并中断在以下调用中当前被阻塞"的go例程

My question is how do i cleanly shutdown the server and interrupt the go-routine which is currently "blocked" in the following call

func(* TCPListener)接受吗?

func (*TCPListener) Accept?

根据接受文档

Accept在侦听器接口中实现Accept方法;它等待下一次调用并返回通用的Conn.

Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.

几乎也没有记录错误.

这就是我想要的.也许将来会帮助某人.请注意,使用select和"c"通道将其与退出通道结合在一起

Here is what i was looking for. Maybe helps someone in the future. Notice the use of select and the "c" channel to combine it with the exit channel

    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
        }
    }