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

huangapple go评论87阅读模式
英文:

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

问题

在Go语言中,net.Listen("tcp", "127.0.0.1:9090")不能满足所有的需求吗?为什么我们还需要net.ListenTCP("tcp", localAddress)?我认为它们在实现上非常相似。

英文:

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.

答案1

得分: 3

Listen函数是对ListenTCPListenUnix的常见抽象。Listen函数以Listener接口的协议特定监听器类型返回。

Listen还提供了将字符串地址转换为ListenTCP和ListenUnix所需的特定地址类型的额外便利性。

如果您已经有TCPAddr或需要使用Listener接口上不可用的TCPListener方法,请使用ListenTCP。

英文:

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.

答案2

得分: 1

net.Listen() 返回一个接口 net.Listener,它只保证支持以下方法:Accept()Close()Addr()

net.ListenTCP() 返回一个类型为 *net.TCPListener 的对象,它支持上述三个方法,因此(鸭子类型)它支持 net.Listener 接口。然而,它还支持更多特定于 TCP 的函数,可以控制连接接受的底层细节。例如,设置 SetDeadline() 等功能。

英文:

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.

huangapple
  • 本文由 发表于 2021年11月3日 11:29:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/69819361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定