Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the different between `Listen` and `ListenTCP`?

Tags:

go

In Go, does net.Listen("tcp", "127.0.0.1:9090") not meet any needs? Why do we still have net.ListenTCP("tcp", localAddress)? I think they are much similar in implementation.

like image 531
Yongqi Z Avatar asked Oct 16 '25 03:10

Yongqi Z


2 Answers

The Listen function is a common abstraction over ListenTCP and ListenUnix. The Listen function returns a protocol specific listener type as a Listener interface.

Listen also provides the extra convenience of converting a string address to the specific address types required by ListenTCP and ListenUnix.

Use ListenTCP if you have TCPAddr in hand or need to use TCPListener methods that are not available on the Listener interface.

like image 101
2 revsuser13631587 Avatar answered Oct 18 '25 20:10

2 revsuser13631587


net.Listen() returns an interface net.Listener that only guarantees it supports the following methods: Accept(), Close() and Addr().

net.ListenTCP() returns a type *net.TCPListener that supports the above three methods so (duck typing) it supports the net.Listener interface. However, it also supports more functions that are specific to TCP and can control low level aspects of the connection acceptance. Things like setting SetDeadline() etc.

like image 28
Tinkerer Avatar answered Oct 18 '25 19:10

Tinkerer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!