在同一台機器上一個端口在某時刻只能被一個應用程序占用。對於WCF服務來說,如果服務器上有多個服務並且這些服務寄宿在不同的應用程序中,我們需要某種途徑來共享它們的端口。下面是一個示例來演示使用TcpBinding進行端口共享。在VS2010中創建兩個WCF服務工程,使用TCP綁定並且使用同一個端口進行部署。
工程1代碼如下:
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
namespace hostTcpPortSharing2
{
class Program
{
static void Main(string[] args)
{
ServiceHost host2 = new ServiceHost(typeof(mywcf.CalculatorService));
NetTcpBinding tcpbind = new NetTcpBinding();
host2.AddServiceEndpoint(typeof(mywcf.ICalculatorService), tcpbind, "net.tcp://localhost:8899/tcp1");
host2.Opened += delegate { Console.WriteLine("net.tcp://localhost:8899/tcp1 Service Start!"); };
host2.Open();
Console.ReadLine();
}
}
}
工程2代碼:
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
namespace hostTcpPortSharing2
{
class Program
{
static void Main(string[] args)
{
ServiceHost host2 = new ServiceHost(typeof(mywcf.CalculatorService));
NetTcpBinding tcpbind = new NetTcpBinding();
host2.AddServiceEndpoint(typeof(mywcf.ICalculatorService), tcpbind, "net.tcp://localhost:8899/tcp2");
host2.Opened += delegate { Console.WriteLine("net.tcp://localhost:8899/tcp2 Service Start!"); };
host2.Open();
Console.ReadLine();
}
}
}
這兩個工程代碼基本一致,相同點就是都用了NetTcpBinding,並且都部署到8899端口,唯一不同的是終結點地址。先運行工程1,再運行工程2。
端口已經被工程1占用,工程2無法使用。
WCF對服務的端口共享提供了支持方法。在端口共享服務開啟的狀態下,當兩個使用同一個端口的服務Open的時候,會注冊到Net.Tcp共享服務中。注冊內容為匹配地址-宿主進程。當客戶端調用的時候會根據請求中的終結點地址轉發到對應的服務進程。開啟Tcp端口的方法很簡單,只需要在TcpBinding的PortSharingEnabled屬性設置為true即可。注意,工程1和工程2都需要設置。代碼如下:
NetTcpBinding tcpbind = new NetTcpBinding(); tcpbind.PortSharingEnabled = true; host.AddServiceEndpoint(typeof(mywcf.ICalculatorService), tcpbind, "net.tcp://localhost:8899/tcp1");
NetTcpBinding tcpbind = new NetTcpBinding(); tcpbind.PortSharingEnabled = true; host.AddServiceEndpoint(typeof(mywcf.ICalculatorService), tcpbind, "net.tcp://localhost:8899/tcp2");
如果用配置文件的方式則為:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="tccpbind" portSharingEnabled="true"></binding>
</netTcpBinding>
</bindings>
<services>
<service name="mywcf.CalculatorService">
<endpoint address="net.tcp://localhost:8899" binding="netTcpBinding" bindingConfiguration="tccpbind" contract="mywcf.ICalculatorService"></endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
