HOW TO:將 Windows Communication Foundation 服務設為使用連接埠共用

在 Windows Communication Foundation (WCF) 應用程式使用 net.tcp:// 連接埠共用的最簡單方式,是使用 NetTcpBinding 來公開服務。

這項繫結會提供 PortSharingEnabled 屬性,以控制是否針對使用此繫結進行設定的服務啟用 net.tcp:// 連接埠共用。

下列程序將說明如何使用 NetTcpBinding 類別來開啟統一資源識別元 (URI) 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 新增服務端點,該服務會使用連接埠共用啟用之 NetTcpBinding,並在端點位址 URI "net.tcp://localhost/MyService" 上進行接聽。

    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")
    

    注意

    此範例使用預設 TCP 連接埠號碼 808,因為端點位址 URI 並未指定不同的連接埠號碼。 由於已在傳輸繫結程序上明確啟用連接埠共用,此服務可與其他處理序中的其他服務共用連接埠 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>  

另請參閱