WCF实现进程间管道通信Demo分享

 更新时间:2017年12月15日 15:43:33   作者:秋荷雨翔  
下面小编就为大家分享一篇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; }
 }
}

三、服务端服务接口和实现:

接口:

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, 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();
  }
 }
}

五、客户端数据实体类和服务接口类与服务端相同

六、客户端服务实现:

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();
   }
  }
 }
}

七、客户端调用服务接口:

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("请输入合法的数据");
   }
  }
 }
}

八、工具类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分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • C#中按指定质量保存图片的实例代码

    C#中按指定质量保存图片的实例代码

    这篇文章主要介绍了C#中按指定质量保存图片的实例代码,有需要的朋友可以参考一下
    2013-12-12
  • Unity Shader实现黑幕过场效果

    Unity Shader实现黑幕过场效果

    这篇文章主要为大家详细介绍了Unity Shader实现黑幕过场效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • C# Winform 实现TCP发消息

    C# Winform 实现TCP发消息

    这篇文章主要介绍了C# Winform 实现TCP发消息的示例,帮助大家更好的理解和学习使用c#技术,感兴趣的朋友可以了解下
    2021-03-03
  • Unity UGUI的LayoutElement布局元素组件介绍使用示例

    Unity UGUI的LayoutElement布局元素组件介绍使用示例

    这篇文章主要为大家介绍了Unity UGUI的LayoutElement布局元素组件介绍使用示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • C#使用Lazy<T>实现对客户订单的延迟加载

    C#使用Lazy<T>实现对客户订单的延迟加载

    这篇文章介绍了C#使用Lazy<T>实现对客户订单延迟加载的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-08-08
  • MVVM简化的Messager类实例代码

    MVVM简化的Messager类实例代码

    这篇文章主要给大家介绍了关于MVVM简化的Messager类的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-06-06
  • C#装箱和拆箱的原理介绍

    C#装箱和拆箱的原理介绍

    这篇文章介绍了C#装箱和拆箱的原理,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-03-03
  • C#实现自定义屏保的示例代码

    C#实现自定义屏保的示例代码

    这篇文章主要为大家详细介绍了如何利用C#实现自定义屏保的功能,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以跟随小编一起了解一下
    2022-12-12
  • C#实现UI控件输出日志的方法详解

    C#实现UI控件输出日志的方法详解

    一般情况下,我们的日志文件是用来记录一些关键操作或者异常,并且是后台存储,并不对外开放的,但是也有些时候,需要将一些操作步骤、记录等直接显示在窗体上。本文就将利用UI控件输出日志效果,需要的可以参考一下
    2022-10-10
  • Unity制作图片字体的方法

    Unity制作图片字体的方法

    这篇文章主要为大家详细介绍了Unity制作图片字体的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-12-12

最新评论