一、代碼結構: 二、數據實體類: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using Syste ...
一、代碼結構:
二、數據實體類:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace DataStruct { /// <summary> /// 測試數據實體類 /// </summary> [DataContract] public class TestData { [DataMember] public double X { get; set; } [DataMember] public double Y { get; set; } } }View Code
三、服務端服務介面和實現:
介面:
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using DataStruct; namespace WCFServer { /// <summary> /// 服務介面 /// </summary> [ServiceContract] public interface IClientServer { /// <summary> /// 計算(測試方法) /// </summary> [OperationContract] double Calculate(TestData data); } }View Code
實現:
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using DataStruct; namespace WCFServer { /// <summary> /// 服務實現 /// </summary> [ServiceBehavior()] public class ClientServer : IClientServer { /// <summary> /// 計算(測試方法) /// </summary> public double Calculate(TestData data) { return Math.Pow(data.X, data.Y); } } }View Code
四、服務端啟動服務:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.ServiceModel; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Utils; using WCFServer; namespace 服務端 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { BackWork.Run(() => { OpenClientServer(); }, null, (ex) => { MessageBox.Show(ex.Message); }); } /// <summary> /// 啟動服務 /// </summary> private void OpenClientServer() { NetNamedPipeBinding wsHttp = new NetNamedPipeBinding(); wsHttp.MaxBufferPoolSize = 524288; wsHttp.MaxReceivedMessageSize = 2147483647; wsHttp.ReaderQuotas.MaxArrayLength = 6553600; wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647; wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600; wsHttp.ReaderQuotas.MaxDepth = 6553600; wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600; wsHttp.CloseTimeout = new TimeSpan(0, 1, 0); wsHttp.OpenTimeout = new TimeSpan(0, 1, 0); wsHttp.ReceiveTimeout = new TimeSpan(0, 10, 0); wsHttp.SendTimeout = new TimeSpan(0, 10, 0); wsHttp.Security.Mode = NetNamedPipeSecurityMode.None; Uri baseAddress = new Uri("net.pipe://localhost/pipeName1"); ServiceHost host = new ServiceHost(typeof(ClientServer), baseAddress); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb); ServiceBehaviorAttribute sba = host.Description.Behaviors.Find<ServiceBehaviorAttribute>(); sba.MaxItemsInObjectGraph = 2147483647; host.AddServiceEndpoint(typeof(IClientServer), wsHttp, ""); host.Open(); } } }View Code
五、客戶端數據實體類和服務介面類與服務端相同
六、客戶端服務實現:
using DataStruct; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; using WCFServer; namespace DataService { /// <summary> /// 服務實現 /// </summary> public class ClientServer : IClientServer { ChannelFactory<IClientServer> channelFactory; IClientServer proxy; public ClientServer() { CreateChannel(); } /// <summary> /// 創建連接客戶終端WCF服務的通道 /// </summary> public void CreateChannel() { string url = "net.pipe://localhost/pipeName1"; NetNamedPipeBinding wsHttp = new NetNamedPipeBinding(); wsHttp.MaxBufferPoolSize = 524288; wsHttp.MaxReceivedMessageSize = 2147483647; wsHttp.ReaderQuotas.MaxArrayLength = 6553600; wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647; wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600; wsHttp.ReaderQuotas.MaxDepth = 6553600; wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600; wsHttp.SendTimeout = new TimeSpan(0, 10, 0); wsHttp.Security.Mode = NetNamedPipeSecurityMode.None; channelFactory = new ChannelFactory<IClientServer>(wsHttp, url); foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = 2147483647; } } } /// <summary> /// 計算(測試方法) /// </summary> public double Calculate(TestData data) { proxy = channelFactory.CreateChannel(); try { return proxy.Calculate(data); } catch (Exception ex) { throw ex; } finally { (proxy as ICommunicationObject).Close(); } } } }View Code
七、客戶端調用服務介面:
using DataService; using DataStruct; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Utils; using WCFServer; namespace 客戶端 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //測試1 private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; txtSum.Text = string.Empty; IClientServer client = new ClientServer(); double num1; double num2; double sum = 0; if (double.TryParse(txtNum1.Text, out num1) && double.TryParse(txtNum2.Text, out num2)) { DateTime dt = DateTime.Now; BackWork.Run(() => { sum = client.Calculate(new TestData(num1, num2)); }, () => { double time = DateTime.Now.Subtract(dt).TotalSeconds; txtTime.Text = time.ToString(); txtSum.Text = sum.ToString(); button1.Enabled = true; }, (ex) => { button1.Enabled = true; MessageBox.Show(ex.Message); }); } else { button1.Enabled = true; MessageBox.Show("請輸入合法的數據"); } } //測試2 private void button2_Click(object sender, EventArgs e) { button2.Enabled = false; txtSum.Text = string.Empty; IClientServer client = new ClientServer(); double num1; double num2; double sum = 0; if (double.TryParse(txtNum1.Text, out num1) && double.TryParse(txtNum2.Text, out num2)) { DateTime dt = DateTime.Now; BackWork.Run(() => { for (int i = 0; i < 1000; i++) { sum = client.Calculate(new TestData(num1, num2)); } }, () => { double time = DateTime.Now.Subtract(dt).TotalSeconds; txtTime.Text = time.ToString(); txtSum.Text = sum.ToString(); button2.Enabled = true; }, (ex) => { button2.Enabled = true; MessageBox.Show(ex.Message); }); } else { button2.Enabled = true; MessageBox.Show("請輸入合法的數據"); } } } }View Code
八、工具類BackWork類:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; /** * 使用方法: BackWork.Run(() => //DoWork { }, () => //RunWorkerCompleted { }, (ex) => //錯誤處理 { }); */ namespace Utils { /// <summary> /// BackgroundWorker封裝 /// 用於簡化代碼 /// </summary> public class BackWork { /// <summary> /// 執行 /// </summary> /// <param name="doWork">DoWork</param> /// <param name="workCompleted">RunWorkerCompleted</param> /// <param name="errorAction">錯誤處理</param> public static void Run(Action doWork, Action workCompleted, Action<Exception> errorAction) { bool isDoWorkError = false; Exception doWorkException = null; BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (s, e) => { try { doWork(); } catch (Exception ex) { isDoWorkError = true; doWorkException = ex; } }; worker.RunWorkerCompleted += (s, e) => { if (!isDoWorkError) { try { if (workCompleted != null) workCompleted(); } catch (Exception ex) { errorAction(ex); } } else { errorAction(doWorkException); } }; worker.RunWorkerAsync(); } } }View Code
九、效果圖示: