Golang中使用net.Pipe的io.Reader用法

huangapple go评论91阅读模式
英文:

Golang io.Reader usage with net.Pipe

问题

我正在尝试解决的问题是在网络应用程序中使用io.Reader和io.Writer,而不使用bufio和strings,根据我在网上找到的示例。为了提高效率,我试图避免使用涉及内存复制的操作。

我在playground上创建了一个使用net.Pipe的测试应用程序(https://play.golang.org/p/-7YDs1uEc5)。有一个数据源和一个数据接收器,它们通过一对net.Pipe连接进行通信(模拟网络连接),并在远端设置了一个回环来将数据原样返回给我们。

程序能够将发送的数据传输到回环代理,但据我所见,写回到连接的操作被锁住了;它肯定没有完成。此外,接收器在数据接收器中根本没有接收到任何数据。

我无法弄清楚为什么写操作无法进行,因为它与能够正常工作的路径完全对称。我编写了其他使用双向网络连接的测试系统,但一旦我停止使用bufio和ReadString,就会遇到这个问题。我查看了这些代码,但找不到我漏掉的地方。

提前感谢您的帮助。

英文:

The problem I'm trying to solve is using io.Reader and io.Writer in a net application without using bufio and strings as per the examples I've been able to find online. For efficiency I'm trying to avoid the memcopys those imply.

I've created a test application using net.Pipe on the play area (https://play.golang.org/p/-7YDs1uEc5). There is a data source and sink which talk through a net.Pipe pair of connections (to model a network connection) and a loopback on the far end to reflect the data right back at us.

The program gets as far as the loopback agent reading the sent data, but as far as I can see the write back to the connection locks; it certainly never completes. Additionally the receiver in the Sink never receives any data whatsoever.

I can't figure out why the write cannot proceed as it's wholly symmetrical with the path that does work. I've written other test systems that use bi-directional network connections but as soon as I stop using bufio and ReadString I encounter this problem. I've looked at the code of those and can't see what I've missed.

Thanks in advance for any help.

答案1

得分: 2

问题出在第68行:

data_received := make([]byte, 0, count)

这一行创建了一个长度为0、容量为count的切片。由于长度为0,调用Read函数不会读取任何数据。而调用Write函数会阻塞,因为数据从未被读取。

修复这个问题,将该行改为:

data_received := make([]byte, count)

playground示例

请注意,"Finished Writing"可能不会被打印出来,因为程序可能在dataSrc执行完成之前就退出了。

英文:

The issue is on line 68:

data_received := make([]byte, 0, count)

This line creates a slice with length 0 and capacity count. The call to Read does not read data because the length is 0. The call to Write blocks because the data is never read.

Fix the issue by changing the line to:

data_received := make([]byte, count)

playground example

Note that "Finished Writing" may not be printed because the program can exit before dataSrc finishes executing.

huangapple
  • 本文由 发表于 2016年9月7日 01:53:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/39355092.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定