gpt4 book ai didi

.net - 如何找到 NetTcpBinding (WCF) 可用的 TCP 端口(以便服务器可以绑定(bind)到它)

转载 作者:可可西里 更新时间:2023-11-01 02:30:34 25 4
gpt4 key购买 nike

Find the next TCP port in .Net说明了如何在原始 .net 中执行此操作,但没有说明如何使用 WCF 安全地执行此操作。

在我的单元测试中,我需要使用 NetTcpBinding,我不想硬编码它正在使用的端口

因此,如何让 NetTcpBinding 在我的 ServiceHost 中使用时自动选择空闲端口?

我怎样才能让它告诉我它选择的端口(或完整端点地址)?

或者我如何使用 .NET 找到几个对服务器绑定(bind)有效的端口?


鉴于我的赏金没有带来任何新的答案,我认为我们可以假设没有好的答案。

最佳答案

您不需要推出自己的端口查找逻辑 - 如果您将其指定为 0,Windows 将选择一个空闲端口。然后您可以通过询问调度程序找出分配了哪个端口,如下所示:

// Specify port 0, this will cause Windows to choose a free port
var baseUri = new Uri("net.tcp://" + Dns.GetHostEntry("").HostName + ":0");
host = new WebServiceHost(typeof(MyService));
var endPoint = host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), baseUri);

// Tell WCF to actually bind to a free port instead of 0
endPoint.ListenUriMode = ListenUriMode.Unique;

host.Open();

// Now that the host has bound to a specific port, we can find out which one it chose
return host.ChannelDispatchers.First().Listener.Uri;

关于.net - 如何找到 NetTcpBinding (WCF) 可用的 TCP 端口(以便服务器可以绑定(bind)到它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1803065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com