WCF - 實作 WCF 服務啟動器

摘要:WCF - 實作 WCF 服務啟動器

在前一篇<WCF - 小呆的第一支 WCF 程式誕生>中是使用 IIS 的方式來提供 WCF 的服務,而這一次將換一種方式,甚麼方式呢!? 將使用一個 WinForm 來控制 WCF 服務是否要提供服務,而服務是用 net.tcp 的方式來通訊,當然此篇的範例還是會有 config 的設定,以下就來看看唄...

規劃:
1.MyClientConsole:呼叫 WCF 服務的 Client 端程式
2.MyServiceHost:實作 WCF 服務的啟動與停止
3.MyWcfInterface:定義 Entities 及 Interface
4.MyWcfService:實作 Interface 功能

步驟一:新增一個名為「MyWcfSample」方案,並且再新增一個名為「MyWcfInterface」的專案;並如下圖所示建立相關的檔案


步驟二:實作「CompositeType.cs」的內容

Code:

using System.ServiceModel;
using System.Runtime.Serialization;

namespace MyWcfInterface.Entities
{
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

步驟三:實作「MyInterface.cs」的內容

Code:

using System.ServiceModel;
using MyWcfInterface.Entities;

namespace MyWcfInterface
{
    [ServiceContract]
    public interface MyInterface
    {
        [OperationContract]
        string GetDateTime();

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
    }
}

步驟四:在方案中,建立一個名為「MyWcfService」的專案,來實作 Interface 功能


步驟五:實作「MyService.cs」內容

Code:

using MyWcfInterface;
using System.ServiceModel;
using MyWcfInterface.Entities;
using System.Runtime.Serialization;

namespace MyWcfService
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, MaxItemsInObjectGraph = int.MaxValue, IncludeExceptionDetailInFaults = true)]
    public class MyService : MyInterface
    {
        public string GetDateTime()
        {
            return string.Format("現在時間:{0}", DateTime.Now.ToString());
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += " Love Peggy...";
            }
            return composite;
        }
    }
}

步驟六:在方案中,建立一個名為「MyServiceHost」的專案,來實作 WCF 服務啟動器


步驟七:佈署一下 Form1 的畫面


步驟八:實作 WCF 服務器的功能

Code:

using MyWcfService;
using MyWcfInterface;
using System.ServiceModel;
using MyWcfInterface.Entities;
using System.Runtime.Serialization;

namespace MyServiceHost
{
    public partial class Form1 : Form
    {
        ServiceHost wcf_Host = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                wcf_Host = new ServiceHost(typeof(MyWcfService.MyService));
                wcf_Host.Opened += new EventHandler(wcf_Host_Opened);
                wcf_Host.Closed += new EventHandler(wcf_Host_Closed);
                wcf_Host.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                wcf_Host.Close();
                wcf_Host.Opened -= new EventHandler(wcf_Host_Opened);
                wcf_Host.Closed -= new EventHandler(wcf_Host_Closed);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Enabled = true;
            button2.Enabled = false;
        }

        void wcf_Host_Opened(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            this.button2.Enabled = true;
        }

        void wcf_Host_Closed(object sender, EventArgs e)
        {
            this.button1.Enabled = true;
            this.button2.Enabled = false;
        }
    }
}

步驟九:使用「SvcConfigEditor.exe」來設定 WCF 服務的通訊資訊,設定完成後,會在「App.config」中看到以下的內容

Code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="test" name="MyWcfService.MyService">
        <endpoint address="net.tcp://localhost:5566/TcpBinding" binding="netTcpBinding"
          name="NetTcpBinding_IServiceClass" contract="MyWcfInterface.MyInterface" />
      </service>
    </services>
    <bindings>
      <netTcpBinding>
        <binding name="NetTcpBinding_IServiceClass" />
      </netTcpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="test" >
          <serviceMetadata/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

步驟十:在方案中,建立一個名為「MyClientConsole」的專案,來呼叫 WCF 服務


步驟十一:使用「SvcConfigEditor.exe」來設定取得 WCF 服務器所提供的功能,設定完成後,會在「App.config」中看到以下的內容

Code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <client>
            <endpoint address="net.tcp://localhost:5566/TcpBinding" binding="netTcpBinding"
                bindingConfiguration="" contract="MyWcfInterface.MyInterface"
                name="Windows_Console_Host_TcpBinding" />
        </client>
    </system.serviceModel>
</configuration>

步驟十二:在「Program.cs」實作呼叫 WCF 服務

Code:

using System.ServiceModel;
using MyWcfInterface;
using MyWcfInterface.Entities;

namespace MyClientConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelFactory<MyInterface> channelFactory = new ChannelFactory<MyInterface>("Windows_Console_Host_TcpBinding");

            MyInterface myInterface = channelFactory.CreateChannel();

            Console.WriteLine(myInterface.GetDateTime().ToString());

            Console.WriteLine();
           
            Console.WriteLine();

            CompositeType ct1 = new CompositeType();

            ct1.BoolValue = true;

            ct1.StringValue = "Danny";

            CompositeType ct2 = myInterface.GetDataUsingDataContract(ct1);

            Console.WriteLine(ct2.StringValue);

            Console.ReadKey();
        }
    }
}

結果:

1.執行 WCF 服務啟動器


2.如何得知 localhost:5566 是否正常監聽呢!?可以在 DOS Command 下使用「netstat -na」來得知


3.執行「MyClientConsole」


參考:
WCF高級編成(書)
WCF技術剖析(書)