天天看點

WCF初探 --- 多個契約、多個服務 綁定一個端口

目的:

在1個wcf 服務應用程式中,包含多個服務契約 IService1.cs  IService2.cs ....等。在winform窗體作為宿主,啟動wcf,并綁定 IService1.cs  IService2.cs 到同一個端口5031下面。

 步驟

1、正常建立wcf 應用程式,然後添加wcf 服務,這時包含2個契約。

WCF初探 --- 多個契約、多個服務 綁定一個端口

2、添加一個winform項目,并引用-添加服務引用,發現上述wcf服務。這是涉及到wcf的啟動方式了,有程式設定、配置檔案配置2種啟動方式。

方法1、配置檔案方式 ,修改 winform項目-app.config如下:

要注意 :

        <baseAddresses>

                 <!--<add baseAddress="http://10.76.37.152:5031/"/>-->

                  <!--如果是綁定多個服務到1個端口,這裡不寫位址,在程式中指定-->

          </baseAddresses>

如果是啟動1個服務綁定到1個端口,上面的baseAddress要留下,如果是綁定多個服務到1個端口,如本文,則此處注釋掉,在程式中指明,如下:

private void btnStart_Click(object sender, EventArgs e)
        {
            host1 = new ServiceHost(typeof(CCWorkbench.Server.Service1), new Uri("http://10.76.37.152:5031/ser1"));
            host1.Open();

            host2 = new ServiceHost(typeof(CCWorkbench.Server.Service2), new Uri("http://10.76.37.152:5031/ser2"));
            host2.Open();

            //this.ServiceStart();
            this.label1.Text = "服務啟動成功!";
        }
           

配置檔案如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  
  <system.serviceModel>
    <services>
      
      
      <!--Service1 的啟動-->
      <service name="CCWorkbench.Server.Service1" behaviorConfiguration="behavior">
        <host>
          <baseAddresses>
            <!--<add baseAddress="http://10.76.37.152:5031/"/>-->
            <!--如果是綁定多個服務到1個端口,這裡不寫位址,在程式中指定-->
          </baseAddresses>
        </host>
        <endpoint address=""   binding="wsHttpBinding" contract="CCWorkbench.Server.IService1"></endpoint>
      </service>
    
     <!--Service2 的啟動-->
      <service name="CCWorkbench.Server.Service2" behaviorConfiguration="behavior">
        <host>
          <baseAddresses>
            <!--<add baseAddress="http://10.76.37.152:5031/"/>-->
            <!--如果是綁定多個服務到1個端口,這裡不寫位址,在程式中指定-->
          </baseAddresses>
        </host>
        <endpoint address=""   binding="wsHttpBinding" contract="CCWorkbench.Server.IService2"></endpoint>
      </service>
    
       </services>
    
      
    <behaviors>
      <serviceBehaviors>
        <behavior name="behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
 
  </system.serviceModel>
</configuration>
           

此時,啟動宿主,開啟服務,可以在 http://10.76.37.152:5031/ser1  通路 Service1 服務,在http://10.76.37.152:5031/ser2  通路Service2 服務。

WCF初探 --- 多個契約、多個服務 綁定一個端口

方法2、程式設定啟動多個服務

首先,winform的配置檔案中不要增加内容,保持app.config預設的狀态,

程式中 如下:我覺得關鍵是   ServiceHost serviceHost = new ServiceHost(item.Value, new Uri(endpointAddress)); 這句話中的 new Uri(endpointAddress) ,指定了位址。

private List<ServiceHost> serviceHosts = new List<ServiceHost>();
        private void ServiceStart()
        {
            if (serviceHosts != null)
            {
                foreach (ServiceHost t in serviceHosts)
                {
                    if (t != null)
                        t.Close();
                }
            }
            else
            {
                serviceHosts = new List<ServiceHost>();
            }

            string serviceAddress = string.Format("http://{0}:{1}", "10.76.37.152", "5031");
            Dictionary<Type, Type> sevtypes = new Dictionary<Type, Type>();

            sevtypes.Add(typeof(CCWorkbench.Server.IService1), typeof(CCWorkbench.Server.Service1));
            sevtypes.Add(typeof(CCWorkbench.Server.IService2), typeof(CCWorkbench.Server.Service2));

            string endpointAddress = string.Empty;
            string tName = string.Empty;
            StringBuilder msgService = new StringBuilder();
            foreach (var item in sevtypes)
            {
                tName = item.Key.Name.Substring(1);
                endpointAddress = serviceAddress + tName;
                if (!serviceAddress.EndsWith("/"))
                    endpointAddress = string.Format("{0}/{1}", serviceAddress, tName);
                //下面這句重要,設定了URL位址。是關鍵。
                ServiceHost serviceHost = new ServiceHost(item.Value, new Uri(endpointAddress));
                //加載中繼資料結點

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                serviceHost.Description.Behaviors.Add(smb);
                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                WSHttpBinding wsb = new WSHttpBinding();
                wsb.Security.Mode = SecurityMode.None;
                serviceHost.AddServiceEndpoint(item.Key, wsb, endpointAddress);

                //加載NetTcpBinding結點
                //NetTcpBinding netTcpBinding = new NetTcpBinding();
                //netTcpBinding.Security.Mode = SecurityMode.None;
                //netTcpBinding.ReceiveTimeout = TimeSpan.Parse("00:10:00");
                //netTcpBinding.MaxBufferPoolSize = 2147483647;
                //netTcpBinding.MaxBufferSize = 2147483647;
                //netTcpBinding.MaxConnections = 10;
                //netTcpBinding.ReaderQuotas.MaxDepth = 2147483647;
                //netTcpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
                //netTcpBinding.ReaderQuotas.MaxArrayLength = 2147483647;
                //netTcpBinding.ReaderQuotas.MaxBytesPerRead = 2147483647;
                //netTcpBinding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
                //netTcpBinding.MaxReceivedMessageSize = 2147483647;
                //serviceHost.AddServiceEndpoint(item.Key, netTcpBinding, endpointAddress);


                serviceHost.Opened += delegate
                {
                    msgService.AppendLine(string.Format("{0}開始監聽 Uri 為 :{1}/mex", tName, endpointAddress.ToString()));
                };
                serviceHost.Open();
                serviceHosts.Add(serviceHost);
            }
        }
           

方法3:後來測試發現的,其實如方法1,隻要在baseAddress的最後,增加别名就可以綁定2個服務到1個端口,配置檔案關鍵部分如下: <add baseAddress="http://10.76.37.152:5031/ser1"/>    <add baseAddress="http://10.76.37.152:5031/ser2"/> 是重點,增加了ser1  ser2  ,

程式中和啟動單個服務的寫法一樣,就可以綁定2個服務到1個端口。

private void btnStart_Click(object sender, EventArgs e)
        {
            //host1 = new ServiceHost(typeof(CCWorkbench.Server.Service1), new Uri("http://10.76.37.152:5031/ser1"));
            host1 = new ServiceHost(typeof(CCWorkbench.Server.Service1));
            host1.Open();

            //host2 = new ServiceHost(typeof(CCWorkbench.Server.Service2), new Uri("http://10.76.37.152:5031/ser2"));
            host2 = new ServiceHost(typeof(CCWorkbench.Server.Service2));
            host2.Open();

            //this.ServiceStart();
            this.label1.Text = "服務啟動成功!";
        }
           
<!--Service1 的啟動-->
      <service name="CCWorkbench.Server.Service1" behaviorConfiguration="behavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://10.76.37.152:5031/ser1"/>
            <!--如果是綁定多個服務到1個端口,這裡不寫位址,在程式中指定-->
          </baseAddresses>
        </host>
        <endpoint address=""   binding="wsHttpBinding" contract="CCWorkbench.Server.IService1"></endpoint>
      </service>
    
     <!--Service2 的啟動-->
      <service name="CCWorkbench.Server.Service2" behaviorConfiguration="behavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://10.76.37.152:5031/ser2"/>
            <!--如果是綁定多個服務到1個端口,這裡不寫位址,在程式中指定-->
          </baseAddresses>
        </host>
        <endpoint address=""   binding="wsHttpBinding" contract="CCWorkbench.Server.IService2"></endpoint>
      </service>
           

完成,效果如方法1.

初學,有很多地方也不明白。

參考文章:https://www.cnblogs.com/luomingui/archive/2012/09/06/2674220.html