登录
首页 >  Golang >  Go问答

解析 go-shadowsocks2 中的中继功能

来源:stackoverflow

时间:2024-02-19 21:36:21 222浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《解析 go-shadowsocks2 中的中继功能》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

// 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)是什么意思?

带有时间参数的 setdeadline.now() 似乎不寻常,任何人都可以帮助我理解这一点吗?


解决方案


这可能会有所帮助,来自 net.Conn 文档:

看起来有两个 goroutine 将数据从一个连接复制到另一个连接。当其中任一操作的源连接关闭时,该复制操作将终止,但另一个复制操作将被阻止。根据net.Conn文档,通过设置超时会导致阻塞的复制操作失败,从而解除阻塞gouroutine。

到这里,我们也就讲完了《解析 go-shadowsocks2 中的中继功能》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>