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 := 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:
readWriteData(rw) has two tasks:
- read incoming data from
- process this data and send a feedback message also via
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.
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
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?