Home > Software engineering >  What is the different between `Listen` and `ListenTCP` in golang
What is the different between `Listen` and `ListenTCP` in golang

Time:11-03

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related