如何使用 NetTcpBinding (WCF) 找到空闲的 TCP 端口(以便服务器可以绑定到它)
在 .Net 中查找下一个 TCP 端口 说明了如何在raw .net,但不知道如何使用 WCF 安全地实现这一点。
在我的单元测试中,我需要使用 NetTcpBinding,我不希望对其正在使用的端口进行硬编码。
因此,如何让 NetTcpBinding 在我的 ServiceHost 中使用时自动选择空闲端口?
我怎样才能让它告诉我它选择的端口(或完整端点地址)?
或者我如何使用 .NET 找到一些对服务器绑定有效的端口?
鉴于我的赏金没有带来任何新的答案,我认为我们可以假设没有好的答案。
Find the next TCP port in .Net says how to do this in raw .net, but not how to safely to this with WCF.
In my unit tests, I need to use the NetTcpBinding, I do not wish to hard code the port it is using.
Therefore how can I get the NetTcpBinding to automatically choose a free port when used in my ServiceHost?
How can I get it to tell me the port (or full endpoint address) it has chosen?
Or how can I using .NET find a few port that is valid for a server to bind to?
Given that my bounty did not lead to any new answers, I think we can assume there is no good answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不需要滚动自己的端口查找逻辑 - 如果您将其指定为 0,Windows 将选择一个空闲端口。然后您可以通过询问调度程序来找出分配了哪个端口,如下所示:
You don't need to roll your own port-finding logic - Windows will choose a free port if you specify it as 0. Then you can find out which port was assigned by interrogating the dispatchers, like so:
将端口设置为零。这允许操作系统为您选择一个可用的端口。如果需要确定使用了哪个端口,可以在本地绑定后从套接字查询。
Set the port to zero. That allows the OS to pick an available port for you. If you need to determine which port was used, you can query that from the socket after it has been bound locally.
我的做法是:从 1025-2000 范围内的随机端口(任意选择的范围)开始。我尝试绑定它,如果失败,我会捕获异常。然后我向上移动一个端口 (
port = port % 2000 + 1025
) 直到我换行。我没有绑定任何端口,我放弃测试失败。Here's what I do: start with a random port in range 1025-2000 (range chosen arbitrarily). I try to bind it and if it fails I catch the exception. Then I go one port up (
port = port % 2000 + 1025
) until I wrap. I no port is bound, I give up failing the test.4年后..
目前我们有一个解决方案,将
ListenUriMode
设置为Unique
,如 MSDN这里有一个端点配置的小例子
现在下一个问题:如果端口是动态客户怎么知道呢?如此答案中所述,您可以使用WCF DISCOVERY:它需要在服务器和客户端,但它运行良好(唯一的问题是需要几秒钟才能获取它,默认情况下为 20 秒,但我没有问题将其强制为 5)
4 years later..
at the present day we have a solution, setting
ListenUriMode
toUnique
, as stated from MSDNHere a little example of an endpoint configuration
And now the next problem: If the port is dynamic how can clients know it? As stated in THIS ANSWER you can use WCF DISCOVERY: it requires a little configuration on both server and client side but it works well (with the only problem that it takes some seconds to get it, by default 20 seconds but i have no problems forcing it to 5)
当使用随机高端口时,您可能会与想要在程序之后启动的其他服务器进程产生冲突。
只需使用零作为端口号,让操作系统关心保留(unix 上的 /etc/services,不知道 Windows 如何处理它)。
when using a random high port you can generate collisions with other server processes that want to start after your program.
just use zero as the port number and let the os care about reservations (/etc/services on unix, don´t know how windows handles it).