Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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.

like image 442
RishiD Avatar asked Sep 06 '25 23:09

RishiD


1 Answers

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.

like image 134
Burak Serdar Avatar answered Sep 09 '25 20:09

Burak Serdar