WCF实现进程间管道通信Demo

一、代码结构:

二、数据实体类:

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

九、效果图示:

 

 

转载于:https://www.cnblogs.com/s0611163/p/8043157.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以使用WCF(Windows Communication Foundation)来实现进程通信。WCF是一种用于构建分布式应用程序的框架,它提供了一种灵活的方式来实现不同进程的通信。以下是实现WCF进程通信的步骤: 1. 定义服务契约接口:在WCF服务中,首先需要定义一个服务契约接口,该接口定义了服务的操作和数据契约。在服务契约接口中,可以定义需要传递的数据和操作。 2. 实现服务契约接口:在WCF服务中,需要实现定义的服务契约接口。在实现过程中,可以使用回调方法来实现与客户端的通信。通过OperationContext的方法GetCallbackChannel()来获取回调对象,然后使用回调方法进行通信。 3. 配置WCF服务:在配置文件中,需要定义WCF服务的终结点和绑定。终结点定义了服务的地址和协议,绑定定义了服务的通信方式和协议。 4. 创建WCF客户端:在客户端中,需要创建一个WCF客户端对象,并指定服务的终结点和绑定。然后可以通过调用客户端对象的方法来与服务进行通信。 5. 调用WCF服务:在客户端中,可以通过调用WCF客户端对象的方法来调用WCF服务。如果需要使用回调方法,可以在客户端中实现回调契约的接口,并在服务端使用回调方法进行通信。 总结起来,使用WCF实现C#中的进程通信的步骤包括定义服务契约接口、实现服务契约接口、配置WCF服务、创建WCF客户端和调用WCF服务。通过这些步骤,可以实现不同进程的通信。[2][3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值