需要帮助了解go-shadowsocks2中的此中继功能

问题描述

// relay copies between left and right bidirectionally. Returns number of
// bytes copied from right to left,from left to right,and any error occurred.
func relay(left,right net.Conn) (int64,int64,error) {
        type res struct {
                N   int64
                Err error
        }
        ch := make(chan res)

        go func() {
                n,err := io.copy(right,left)
                right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
                left.SetDeadline(time.Now())  // wake up the other goroutine blocking on left
                ch <- res{n,err}
        }()

        n,err := io.copy(left,right)
        right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
        left.SetDeadline(time.Now())  // wake up the other goroutine blocking on left
        rs := <-ch

        if err == nil {
                err = rs.Err
        }
        return n,rs.N,err
}

这来自go-shadowsocks2项目,但是,我无法理解left.SetDeadline(time.Now())部分,注释(唤醒左侧的其他goroutine阻塞)是什么意思? / p>

带有time.Now()参数的SetDeadline似乎很不寻常,有人可以帮我理解吗?

解决方法

从net.Conn文档中这可能会有所帮助:

最后期限是指绝对时间,在该绝对时间之后,I / O操作 失败而不是阻止。截止日期适用于所有未来 和待处理的I / O,而不仅仅是紧随其后的对 读或写。超过最后期限后, 可以通过设置将来的期限来刷新连接。

似乎有两个goroutine将数据从一个连接复制到另一个连接。当其中一个操作的源连接关闭时,该复制操作将终止,但另一个复制操作将被阻止。根据net.Conn文档,通过设置超时将导致被阻止的复制操作失败,从而取消对gouroutine的阻止。