duanhuan3705 2016-04-21 22:44
浏览 47
已采纳

在Go中检测丢失的连接的正确方法是什么?

I am working with a Go HTTP server implementation that reads an upload from a mobile client. However, I'm experiencing problems where because of a long keep-alive, the server will hang reading the request buffer for quite a long time if the mobile client goes offline (as often happens).

What is the proper way to detect a dropped connection and close the input buffer?

  • 写回答

2条回答 默认 最新

  • duan0821 2016-04-22 21:14
    关注

    Because I wanted to drop the connection only when writes stop (and quickly, so that I can record the data received so far and allow the client to resume), the ReadTimeout isn't the right solution for me.

    I found the answer in this gist. You need to set a read on the connection itself.

    package nettimeout

    import (
        "net"
        "time"
    )
    
    // Listener wraps a net.Listener, and gives a place to store the timeout
    // parameters. On Accept, it will wrap the net.Conn with our own Conn for us.
    type Listener struct {
        net.Listener
        ReadTimeout  time.Duration
        WriteTimeout time.Duration
    }
    
    func (l *Listener) Accept() (net.Conn, error) {
        c, err := l.Listener.Accept()
        if err != nil {
            return nil, err
        }
        tc := &Conn{
            Conn:         c,
            ReadTimeout:  l.ReadTimeout,
            WriteTimeout: l.WriteTimeout,
        }
        return tc, nil
    }
    
    // Conn wraps a net.Conn, and sets a deadline for every read
    // and write operation.
    type Conn struct {
        net.Conn
        ReadTimeout  time.Duration
        WriteTimeout time.Duration
    }
    
    func (c *Conn) Read(b []byte) (int, error) {
        err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
        if err != nil {
            return 0, err
        }
        return c.Conn.Read(b)
    }
    
    func (c *Conn) Write(b []byte) (int, error) {
        err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
        if err != nil {
            return 0, err
        }
        return c.Conn.Write(b)
    }
    
    func NewListener(addr string, readTimeout, writeTimeout time.Duration) (net.Listener, error) {
        l, err := net.Listen("tcp", addr)
        if err != nil {
            return nil, err
        }
    
        tl := &Listener{
            Listener:     l,
            ReadTimeout:  readTimeout,
            WriteTimeout: writeTimeout,
        }
        return tl, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行