RishiD
RishiD

Reputation: 2168

Method to allow Go Routine select on net.Conn and a channel?

I feel like this must be a common Go pattern but can't seem to find a solution.

Assume there is a Go application that is making outbound TCP connections. I will be using net.Dial and once connected spawn a Go routine to handle the socket (net.Conn). This is pretty simple and common. What I am trying to figure out is what is the best method to have this Go routine have a channel it is reading and writing messages on that come from this socket? select only is able to wait on a channel and not a net.Conn. Do I poll the socket for data and then check the channel for data? This seems incredibly inefficient.

Upvotes: 3

Views: 2143

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51632

A common solution to this problem is to create two goroutines: one reads from the socket and writes to the channel, and the other reads from the channel and writes to the socket. The goroutine that reads from the socket should terminate when the socket closes, and signal the other goroutine (by canceling a context or closing a channel) so it stops waiting on the channel.

Upvotes: 2

Related Questions