英文:
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函数是对ListenTCP和ListenUnix的常见抽象。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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论