方法 : ポート共有を使用するように Windows Communication Foundation サービスを構成する

Windows Communication Foundation (WCF) アプリケーションで net.tcp:// ポート共有を使用する最も簡単な方法は、NetTcpBinding を使用してサービスを公開することです。

このバインディングは、PortSharingEnabled プロパティを提供します。このプロパティは、このバインディングを使用して構成されるサービスに対して net.tcp:// ポート共有を有効にするかどうかを制御します。

以下の手順では、NetTcpBinding クラスを使用して URI (Uniform Resource Identifier)、net.tcp://localhost/MyService にあるエンドポイントを開く方法を示します。最初にコードを使用する場合の手順を示し、次に構成要素を使用する場合の手順を示します。

コードで NetTcpBinding の net.tcp:// ポート共有を有効にするには

  1. IMyService というコントラクトを実装するサービスを作成し、MyService という名前を付けます。

    [ServiceContract]
    interface IMyService
    {
    
       //Define the contract operations.
    }
    
    class MyService : IMyService
    {
    
    //Implement the IMyService operations.
    }
    
    <ServiceContract()> _
    Friend Interface IMyService
    
        'Define the contract operations.
    
    End Interface
    
    Friend Class MyService
        Implements IMyService
    
        'Implement the IMyService operations.
    
    End Class
    
  2. NetTcpBinding クラスのインスタンスを作成し、PortSharingEnabled プロパティを true に設定します。

    NetTcpBinding portsharingBinding = new NetTcpBinding();
    portsharingBinding.PortSharingEnabled = true;
    
    Dim portsharingBinding As New NetTcpBinding()
    portsharingBinding.PortSharingEnabled = True
    
  3. ServiceHost を作成し、ポート共有を有効にした MyService を使用し、エンドポイント アドレス URI "net.tcp://localhost/MyService" をリッスンする NetTcpBinding のサービス エンドポイントを追加します。

    ServiceHost host = new ServiceHost( typeof( MyService ) );
    host.AddServiceEndpoint( typeof( IMyService ), portsharingBinding,"net.tcp://localhost/MyService" );
    
    
    Dim host As New ServiceHost(GetType(MyService))
    host.AddServiceEndpoint(GetType(IMyService), portsharingBinding, "net.tcp://localhost/MyService")
    

    注意

    このエンドポイント アドレス URI は異なるポート番号を指定しないため、この例では既定の TCP ポートである 808 を使用します。 トランスポート バインディングでポート共有が明示的に有効になっているため、このサービスはポート 808 を他のプロセスの他のサービスと共有できます。 ポート共有が許可されておらず、既に別のアプリケーションがポート 808 を使用している場合は、このサービスを開こうとすると AddressAlreadyInUseException がスローされます。

構成で NetTcpBinding の net.tcp:// ポート共有を有効にするには

  1. 次の例では、構成要素を使用してポート共有を有効にし、サービス エンドポイントを追加します。
<system.serviceModel>  
  <bindings>  
    <netTcpBinding name="portSharingBinding"
                   portSharingEnabled="true" />  
  </bindings>  
  <services>  
    <service name="MyService">  
        <endpoint address="net.tcp://localhost/MyService"  
                  binding="netTcpBinding"  
                  contract="IMyService"  
                  bindingConfiguration="portSharingBinding" />  
    </service>  
  </services>  
</system.serviceModel>  

関連項目