dongshuang0011 2017-01-13 17:11
浏览 32
已采纳

紧密循环泄漏阅读器

I have the following code that I think is leaking heavily. And analysing it I suspect that the defer r.Close() is never called.

Would there be a better way of using the Reader and gzip here at all?

// Read client data from channel
func (c *Client) listen() {
    timeoutDuration := 30 * time.Second

    reader := bufio.NewReader(c.conn)

    clientBuffer := new(bytes.Buffer)

    for {
        c.conn.SetReadDeadline(time.Now().Add(timeoutDuration))

        byte, err := reader.ReadByte()

        if err != nil {
            c.conn.Close()
            c.server.onClientConnectionClosed(c, err)
            return
        }

        clientBuffer.WriteByte(byte)
        packet := popPacketFromBuffer(clientBuffer)

        if packet != nil {
            packetBuffer := bytes.NewBuffer(packet)

            r, _ := gzip.NewReader(packetBuffer)
            defer r.Close()

            b, err := ioutil.ReadAll(r)
            if err != nil {
                log.Fatal(err)
            }

            c.server.onNewMessage(c, b)
        }

    }
}
  • 写回答

1条回答 默认 最新

  • duanshan5259 2017-01-13 17:16
    关注

    Your problem is that defer functions are only called at the end of the function. Not the loop. So, yes, it is probable that they stay open.

    One method would be to encapsulate your tight-loop into a function.

    func uncompress(packet []byte) ([]byte, error) {
        r, _ := gzip.NewReader(bytes.NewBuffer(packet))
        defer r.Close()
        return ioutil.ReadAll(r)
    }
    
    // Read client data from channel
    func (c *Client) listen() {
        /* … */
    
        for {
            /* … */
    
            if packet != nil {
                b, err := uncompress(packet)
                if err != nil {
                    log.Fatal(err)
                }
                c.server.onNewMessage(c, b)
            }
    
        }
    }
    

    Another would be to unroll the defer call and do it manually.

    // Read client data from channel
    func (c *Client) listen() {
        /* … */
    
        for {
            /* … */
    
            if packet != nil {
                r, _ := gzip.NewReader(bytes.NewBuffer(packet))
                b, err := ioutil.ReadAll(r)
                if err != nil {
                    log.Fatal(err)
                }
                r.Close()
                c.server.onNewMessage(c, b)
            }
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题