2016-11-07 99 views
0

我有两个应用程序,一个使用WCF服务,另一个使用WCF客户端。WCF客户端无法连接到具有动态端口的服务

当我使用静态端口时,它们之间的连接工作正常。

当我传递一个“0”作为端口号时,WCF服务动态获得一个可用的端口。

虽然客户端获取端口并将该端口传递给服务器,但连接始终以“EndpointNotFoundException”和“地址过滤器不匹配”结尾。

我评论说“元数据”绑定出来,因为它没有帮助。

//IP address is determined by code, for simplicity in this example it is hardcoded 
//set port to 0 to get a free port 
var url = $"net.tcp://190.150.140.22:0/UiHost"; 
var UiHost = new ServiceHost(typeof(ShippingUIService), new Uri(url)); 

//var mBehave = new ServiceMetadataBehavior(); 
//UiHost.Description.Behaviors.Add(mBehave); 

var ntb = new NetTcpBinding(SecurityMode.None) { ListenBacklog = 10, MaxConnections = 20, PortSharingEnabled = false }; 

var endPoint = UiHost.AddServiceEndpoint(typeof(Core.IShippingUIService), ntb, ""); 
//UiHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); 
// Tell WCF to actually bind to a free port instead of 0 
endPoint.ListenUriMode = System.ServiceModel.Description.ListenUriMode.Unique; 

UiHost.Open(); 

//Uri is saved, so the client can access the service 
var serviceHostUri = UiHost.ChannelDispatchers.First().Listener.Uri.AbsoluteUri; 
log.Info($"UI Service started. With address {serviceHostUri}"); 

是否有可能这一点的代码,没有返回给定的实际端口号?

UiHost.ChannelDispatchers.First()。Listener.Uri.AbsoluteUri;

感谢您提前的每一个提示。

回答

0

您的服务主机的默认地址过滤器是在不知道动态分配端口的情况下生成的,因此不匹配。最简单的解决方案可能是将您的服务类型(ShippingUIService)设置为使用AddressFilterMode = AddressFilterMode.Any在任何地址上进行响应。

的代码基本位:

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)] 
class ShippingUIService { 
    // Class members 
} 
+0

非常感谢,这有助于! – Hiram