V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
acpanda
V2EX  ›  Go 编程语言

请教一下该代码段的功能

  •  
  •   acpanda · 2017-12-17 16:17:38 +08:00 · 1506 次点击
    这是一个创建于 2293 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请问该段代码,函数实现的功能是什么了?相互调用 io.Copy 的意图是?

    func Join(c Conn, c2 Conn) (int64, int64) {
    	var wait sync.WaitGroup
    
    	pipe := func(to Conn, from Conn, bytesCopied *int64) {
    		defer to.Close()
    		defer from.Close()
    		defer wait.Done()
    
    		var err error
    		*bytesCopied, err = io.Copy(to, from)
    		if err != nil {
    			from.Warn("Copied %d bytes to %s before failing with error %v", *bytesCopied, to.Id(), err)
    		} else {
    			from.Debug("Copied %d bytes to %s", *bytesCopied, to.Id())
    		}
    	}
    
    	wait.Add(2)
    	var fromBytes, toBytes int64
    	go pipe(c, c2, &fromBytes)
    	go pipe(c2, c, &toBytes)
    	c.Info("Joined with connection %s", c2.Id())
    	wait.Wait()
    	return fromBytes, toBytes
    }
    
    9 条回复    2017-12-18 10:33:12 +08:00
    Immortal
        1
    Immortal  
       2017-12-17 16:34:20 +08:00
    这个你得结合 Con 结构体的 reader 和 writer 的实现一起看才能知道哦
    rrfeng
        2
    rrfeng  
       2017-12-17 16:35:48 +08:00 via Android   ❤️ 1
    函数实现的功能就是互相 copy

    至于它能干什么你得问写这个函数的人了
    rrfeng
        3
    rrfeng  
       2017-12-17 16:37:07 +08:00 via Android
    看起来像代理程序转发链接数据的。
    acpanda
        4
    acpanda  
    OP
       2017-12-17 21:52:23 +08:00
    @rrfeng 问题是,互相 copy 不会形成一个环吗?
    acpanda
        5
    acpanda  
    OP
       2017-12-17 21:53:59 +08:00
    @Immortal 如果都是 net.Conn 的实现了?
    acpanda
        6
    acpanda  
    OP
       2017-12-17 21:55:46 +08:00
    @rrfeng 都是实现了 net.Conn 的 reader 和 writer。我的疑惑是,两次调用交换了参数的位置,不会形成一个循环吗?
    rrfeng
        7
    rrfeng  
       2017-12-17 21:57:22 +08:00 via Android
    @acpanda 同一个对象的 reader 和 writer 对应的不一定是同一个 buffer,这么说就明白了吧
    sirgod
        8
    sirgod  
       2017-12-18 08:56:24 +08:00
    tcp 连接是双工的,如果你在同一端先写再读,那么读出来的并不是刚才你写进去的,而是另一端的人写进去的
    JohnSmith
        9
    JohnSmith  
       2017-12-18 10:33:12 +08:00
    一般代理都是这么实现的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1676 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:00 · PVG 08:00 · LAX 17:00 · JFK 20:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.