在一个Windows服务中的单个TCP端口上托管多个WCF服务

Sac*_*hin 7 wcf

下面是我的主机Windows服务的app.config文件片段.

<services>
      <service name="Share.Services.MainService">
        <endpoint address="net.tcp://localhost:8001/MainService" behaviorConfiguration="netTcpBehavior" binding="netTcpBinding" contract="Share.Services.IClaimService" />
      </service>
      <service name="Share.Services.MainMasterPageService">
        <endpoint address="net.tcp://localhost:8001/MainMasterPageService" behaviorConfiguration="netTcpBehavior" binding="netTcpBinding" contract="Share.Services.IMainMasterpageService" />
      </service>
      <service name="Share.Services.SMSService">
        <endpoint address="net.tcp://localhost:8001/SMSService" behaviorConfiguration="netTcpBehavior" binding="netTcpBinding" contract="Share.ServiceContracts.Messaging.ISMSService" />
      </service>
    </services>
Run Code Online (Sandbox Code Playgroud)

有3个wcf服务配置为使用端口8001的TCP端点.在Windows服务中,我使用下面的代码来注册服务主机

private static ServiceHost[] Hosts = null;

public static void Start()
{     
    try
    {
        while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
        {
            System.Threading.Thread.Sleep(1000);
        }
        BaseLog.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        Hosts = new ServiceHost[] 
            {
                new ServiceHost(typeof(MainService)), 
                new ServiceHost(typeof(MainMasterPageService)),
                new ServiceHost(typeof(SMSService)) 
            };

        foreach (ServiceHost host in Hosts)
        {
            RegisterServiceHost(host);
        }

        _log.Info("All Hosts Open");
    }
    catch(Exception e)
    {
        _log.Error( "MainServiceHost", e);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我调用RegisterServiceHost函数的每个ServiceHost对象,此函数的代码如下所示

public static void RegisterServiceHost(ServiceHost host)
{
    var ops = (from e in host.Description.Endpoints
            from o in e.Contract.Operations
            select o).ToList();

    ops.ForEach(
        operation => operation.Behaviors.Add(new MainContextOperationBehavior())
            );

    host.Open();
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,没有任何问题.我的问题是所有服务都共享相同的端口8001.所有服务如何能够共享相同的端口.甚至Net.TCP端口共享服务也未在计算机上启用.我的另一个问题是它会在共享同一端口时对性能产生任何影响.如果我为每项服务提供8001,8002,8003这样的独特端口,那么它的优点是什么.

Mat*_*ton 7

他们可以共享同一个端口,因为他们都有不同的路径.显然,所有的作品,所以WCF主机有足够的智能来找出如何让他们共享端口8001相同的监听套接字然后,它可以请求进行区分,因为请求将包括服务的名称就是WCF的一部分端点配置.

我不认为这会导致任何性能问题,但这完全取决于WCF服务主机的工作方式.