一、代码结构:
二、数据实体类:
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; } }}
三、服务端服务接口和实现:
接口:
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); }}
实现:
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); } }}
四、服务端启动服务:
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,0); wshttp.ReceiveTimeout = new TimeSpan(0,10,0); wshttp.SendTimeout = new TimeSpan(0,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(); } }}
五、客户端数据实体类和服务接口类与服务端相同
六、客户端服务实现:
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,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(); } } }}
七、客户端调用服务接口:
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 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("请输入合法的数据"); } } }}
八、工具类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(); } }}
九、效果图示:
以上这篇WCF实现进程间管道通信Demo分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的WCF实现进程间管道通信Demo分享全部内容,希望文章能够帮你解决WCF实现进程间管道通信Demo分享所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)