关于Socket.Disconnect的问题 [英] Questions on Socket.Disconnect

查看:795
本文介绍了关于Socket.Disconnect的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Socket.Disconnect(bool reuse)使程序可以重用套接字.

我的问题是:

1)如果我们决定重用套接字,是否意味着也将重用相同的本地端点?我要问的是它将保留该套接字的端口,还是只是(我不相信这样做)节省了对象的所有资源?

2)如果实际上只保存资源,是否将它们分配给下一个连接,如果是,发送/接收缓冲区是否会自动刷新或是否有某种方法可以刷新它们? Socket.ShutDown(ShutDown.Both)在断开连接时为我这样做吗?

3)在什么情况下我会使用Socket.Disconnect(false),因为如果目的是重用套接字,那么这会给我带来什么呢?

Socket.Disconnect(bool reuse) according to MSDN enables the program to reuse the socket.

My questions are:

1) If we decide to reuse the socket does that mean it will reuse the same local end point as well? What I''m asking is would it preserve the port for that socket or would it just (I don''t believe it does) save all of the object''s resources ?

2) If in effect it does only save the resources, would they be allocated to the next connection and if so do the send/receive buffers automatically flush or is there some way to flush them? Does Socket.ShutDown(ShutDown.Both) do that for me on disconnect?

3) In what situation would I use Socket.Disconnect(false) because if the purpose is to reuse the socket, then what would this give me?

推荐答案

调用Socket.Disconnect(true)将在内部导致Winsock的DisconnectEx 函数被TF_REUSE_SOCKET参数调用.

来自文档:
Calling Socket.Disconnect(true) will internally result in Winsock''s DisconnectEx function being called with the TF_REUSE_SOCKET parameter.

From the docs:
准备要重新使用的 socket句柄 .当DisconnectEx请求完成时,可以将套接字句柄传递给AcceptEx或ConnectEx函数.
Prepares the socket handle to be reused. When the DisconnectEx request completes, the socket handle can be passed to the AcceptEx or ConnectEx function.



因此,只有套接字句柄可以重复使用.这与您的本地终结点无关.

套接字重用用于相当高级的使用,您可以确切地知道自己在做什么.它通常用于高性能高流量TCP服务器.这个想法是,通过重用套接字,您可以节省一些时间(分配该套接字及其资源通常需要花费的时间).因此,某些服务器开发人员要做的是拥有一个预先创建的套接字池,他们可以在需要时从中拉出套接字.

因此,我认为,对于客户端TCP应用程序,从来没有充分的理由来重用套接字.

简而言之,总是使用 Socket.Disconnect(false),除非您真的知道自己在做什么.

由于某些原因,这没有得到很好的记录,并导致了很多混乱.



So it''s only the socket handle that will be reused. This has nothing to do with your local endpoint.

Socket reuse is meant for fairly advanced use, where you know exactly what you are doing. It''s typically used in high performance heavy traffic TCP servers. The idea being that by reusing a socket, you save some time (the time that would normally have gone into allocating that socket and its resources). So what some server developers do is to have a pre-created socket pool that they pull sockets from as and when required.

So in my opinion, for a client side TCP application there is never a good reason to reuse a socket.

In short, always use Socket.Disconnect(false) unless you really know what you are doing.

For some reason, this is not so well documented and leads to a lot of confusion.


这篇关于关于Socket.Disconnect的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆