Chris Hopkins
Chris Hopkins

Reputation: 1001

Golang io.Reader usage with net.Pipe

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.

Upvotes: 2

Views: 1619

Answers (1)

Thundercat
Thundercat

Reputation: 120941

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.

Upvotes: 2

Related Questions