I am coding p2p stuff using golang. The peers communicate via a buffered stream. Using this stream, they can read and write data from it via rw:

rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))

rw contains the senderID and a message (and some other content that is not important now).

To keep the system open, I have a goroutine that is always listening for new incoming data:

go readWriteData(rw)

This readWriteData(rw) has two tasks:

  1. read incoming data from rw
  2. process this data and send a feedback message also via rw

Incoming data is therefore firstly parsed. Depending on sender and message, an answer is written into rw. The other peers can receive it, parse it, process it and answer again. The message contains key words that make it possible to have a logical flow (a kind of request-response communication).

So far so good. My problem is caused by the fact that this goroutine go readWriteData(rw) contains also two readers that read input from the console/terminal:

reader := bufio.NewReader(os.Stdin)

I need those readers for the 2nd task, to process the data and send a feedback message. The first reader is used to start the conversation. Depending on what is the input from the terminal, a new communication starts. This should be always open for all nodes. The second reader is needed to provide a certain answer in the terminal for a given request. Depending on the input from the terminal, the data is differently processed and different answers are sent via rw.

This kind of request-response communication using two readers in a goroutine does not work properly:

For example: User 1 starts the communication typing something into the terminal and sending a request. User 1 and 2 both receive it immediatly (goroutine). And here comes the problem: Both receive data in the goroutine and the first reader starts again waiting for input. But in this case, I need the second reader to answer the request.

Hence, there is the problem that those two reader block the flow within the goroutine go readWriteData(rw). How can I solve this?

0 Answers