When can multiple ServiceHost instances share the same port?
-
05-02-2021 - |
Question
Our application server exposes 5 WCF services over the net.tcp transport, all on the same port. We've been hosting these during development using WcfSvcHost and I've never had to think about how these manage to use the same port.
We're moving them to a Windows Service now, and now I'm instantiating the ServiceHost instances myself. One of the services uses Streamed TransferMode over Tcp.
When starting these services using a configuration file with WcfSvcHost, they work fine. But in our service it complains about the port being in use.
Should it be possible for the streamed service to use the same port?
Solution
I solved the problem eventually, after alot of trial and error with programmatic configuration of the bindings.
It seems that something in the binding stack generated when you create a NetTcpBinding
allows multiple NetTcpBinding
s to share a port. The problem was that I needed to make a custom binding.
The Solution ended up being to create a custom binding based on a NetTcpBinding
. For example:
var lBinding = new NetTcpBinding()
{
SendTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(5),
MaxConnections = 100,
ReliableSession = new OptionalReliableSession
{
Enabled = true,
Ordered = true,
InactivityTimeout = TimeSpan.FromMinutes(30)
},
Security = new NetTcpSecurity
{
Mode = SecurityMode.TransportWithMessageCredential,
Message = new MessageSecurityOverTcp { ClientCredentialType = MessageCredentialType.UserName }
},
MaxReceivedMessageSize = 524288
};
var lCustomBinding = new CustomBinding(lBinding);
// Edit the custom binding elements here
var lEndpoint = new ServiceEndpoint(lContract, lCustomBinding, new EndpointAddress(pServiceHost.BaseAddresses.First()));
OTHER TIPS
I found another solution to for this issue by using a the RoutingService class. Each contract must still be hosted in it's own ServiceHost
, but there can be a RoutingService
sitting on top of all of them - and presenting them over an unified "endpoint". I've also written a codeproject article about it. The example code is also available on Bitbucket.