在不关闭连接的情况下关闭TCP连接的goroutine读数

时间:2018-05-05 09:30:30

标签: sockets go nonblocking channel goroutine

我喜欢Go在内部处理I / O多路复用的方式epoll和另一种机制并自行调度绿色线程(这里是常规例程),可以自由编写同步代码。

我知道TCP套接字为non-blocking,而read在没有可用数据时会给EAGAIN。鉴于此,conn.Read(buffer)将检测到此情况,阻止执行连接读取的go例程,而套接字缓冲区中没有可用的数据。有没有办法在不关闭底层连接的情况下停止这样的例程。我正在使用连接池,因此关闭TCP连接对我来说没有意义,并希望将该连接返回到池中。

以下是模拟此类场景的代码:

func main() {
    conn, _ := net.Dial("tcp", "127.0.0.1:9090")
    // Spawning a go routine
    go func(conn net.Conn) {
        var message bytes.Buffer
        for {
            k := make([]byte, 255) // buffer
            m, err := conn.Read(k) // blocks here 
            if err != nil {
                if err != io.EOF {
                    fmt.Println("Read error : ", err)
                } else {
                    fmt.Println("End of the file")
                }
                break // terminate loop if error
            }
            // converting bytes to string for printing
            if m > 0 {
                for _, b := range k {
                    message.WriteByte(b)
                }
                fmt.Println(message.String())
            }

        }
    }(conn)

    // prevent main from exiting
    select {}
}

如果不可能,我可以采取哪些其他方法:

1)致电syscall.Read并手动处理。在这种情况下,我需要一种方法来检查套接字是否可读,然后再调用syscall.Read,否则我最终会浪费不必要的CPU周期。对于我的场景,我想我可以跳过基于事件的轮询事件并继续调用syscall.Read因为我的用例中总是有数据。

2)任何建议:)

1 个答案:

答案 0 :(得分:1)

func receive(conn net.TCPConn, kill <-chan struct{}) error {
    // Spawn a goroutine to read from the connection.
    data := make(chan []byte)
    readErr := make(chan error)
    go func() {
        for {
            b := make([]byte, 255)
            _, err := conn.Read(b)
            if err != nil {
                readErr <- err
                break
            }
            data <- b
        }
    }()


    for {
        select {
        case b := <-data:
            // Do something with `b`.
        case err := <-readErr:
            // Handle the error.
            return err
        case <-kill:
            // Received kill signal, returning without closing the connection.
            return nil
        }
    }
}

从另一个goroutine向kill发送一个空结构以停止从该连接接收。这是一个在一秒钟后停止接收的程序:

kill := make(chan struct{})
go func() {
    if err := receive(conn, kill); err != nil {
        log.Fatal(err)
    }
}()
time.Sleep(time.Second)
kill <- struct{}{}

这可能不是您正在寻找的内容,因为即使您发送到Read,仍然会在kill上阻止阅读goroutine。但是,处理传入读取的goroutine将终止。