简体   繁体   中英

WCF client cannot connect to service with dynamic port

I have 2 applications one with a WCF Service and another one with a WCF client.

The connection between them works fine when I use a static port.

When I pass a "0" as the port number the WCF service gets dynamically an available port.

Although the client gets the port and passes that port to the server, a connection always ends with an "EndpointNotFoundException" and and "Address Filter Mismatch".

I commented the "MetaData" binding out as it did not help.

//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}");

Is it possible that this bit of code, does not return the actual port number given?

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

Thanks for every hint in advance.

The default address filter for Your service host is generated without knowledge of the dynamically assigned port, and does therefore not match. The easiest solution is probably to set Your service type (ShippingUIService) to respond on any address, using AddressFilterMode = AddressFilterMode.Any.

The essential bit of code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM