Ian*_*ose 9 .net wcf unit-testing tcp nettcpbinding
在.Net中找到下一个TCP端口,说明如何在原始.net中执行此操作,但不知道如何使用WCF安全地执行此操作.
在我的单元测试中,我需要使用NetTcpBinding,我不希望硬编码它正在使用的端口.
因此,如何在我的ServiceHost中使用NetTcpBinding时自动选择一个空闲端口?
我怎样才能告诉我它选择的端口(或完整端点地址)?
或者我如何使用.NET找到一些对服务器有效的端口?
鉴于我的赏金没有带来任何新答案,我认为我们可以假设没有好的答案.
您不需要滚动自己的端口查找逻辑 - 如果您将其指定为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;
Run Code Online (Sandbox Code Playgroud)
我的做法是:从 1025-2000 范围内的随机端口(任意选择的范围)开始。我尝试绑定它,如果失败,我会捕获异常。然后我向上移动一个端口 ( port = port % 2000 + 1025) 直到包好。我没有绑定任何端口,我放弃测试失败。
| 归档时间: |
|
| 查看次数: |
4837 次 |
| 最近记录: |