如何:配置 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()> _
    Friend Interface IMyService
    
        'Define the contract operations.
    
    End Interface
    
    Friend Class MyService
        Implements IMyService
    
        'Implement the IMyService operations.
    
    End Class
    
    [ServiceContract]
    interface IMyService 
    {
    
       //Define the contract operations.
    
    }
    
    class MyService : IMyService 
    {
    
    //Implement the IMyService operations.
    
    
    }
    
  2. 创建 NetTcpBinding 类的一个实例,并将 PortSharingEnabled 属性设置为 true

    Dim portsharingBinding As New NetTcpBinding()
    portsharingBinding.PortSharingEnabled = True
    
    NetTcpBinding portsharingBinding = new NetTcpBinding();
    portsharingBinding.PortSharingEnabled = true;
    
  3. 创建一个 ServiceHost,并在其中为 MyService 添加一个服务终结点,该终结点使用启用了端口共享的 NetTcpBinding 并在终结点地址 URI“net.tcp://localhost/MyService”上进行侦听。

    Dim host As New ServiceHost(GetType(MyService))
    host.AddServiceEndpoint(GetType(IMyService), portsharingBinding, "net.tcp://localhost/MyService")
    
    ServiceHost host = new ServiceHost( typeof( MyService ) );
    host.AddServiceEndpoint( typeof( IMyService ), portsharingBinding,"net.tcp://localhost/MyService" );
    
    ms731810.note(zh-cn,VS.100).gif注意:
    此示例使用默认的 TCP 端口 808,因为终结点地址 URI 未指定其他端口号。由于在传输绑定上显式启用了端口共享,因此该服务可以与其他进程中的其他服务共享端口 808。如果不允许使用端口共享并且其他应用程序已在使用端口 808,则该服务在打开时会引发 AddressAlreadyInUseException

使用配置在 NetTcpBinding 上启用 net.tcp:// 端口共享

  1. 下面的示例演示如何使用配置元素来启用端口共享以及添加服务终结点。
<system.serviceModel>
  <bindings>
    <netTcpBinding name="portSharingBinding" 
                   portSharingEnabled="true" />
  <services>
    <service name="MyService">
        <endpoint address="net.tcp://localhost/MyService"
                  binding="netTcpBinding"
                  contract="IMyService"
                  bindingConfiguration="portSharingBinding" />
    </service>
  </services>
</system.serviceModel>

另请参见

任务

如何:启用 Net.TCP 端口共享服务

概念

Net.TCP 端口共享