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

作者:秋荷雨翔 时间:2022-10-22 04:20:06 

一、代码结构:

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分享

来源:http://www.cnblogs.com/s0611163/archive/2017/12/15/8043157.html

标签:WCF,进程间,管道,通信
0
投稿

猜你喜欢

  • Java传入用户名和密码并自动提交表单实现登录到其他系统的实例代码

    2023-09-20 00:40:46
  • Java设计模式之抽象工厂模式

    2022-05-30 12:45:16
  • C#清除字符串内空格的方法

    2023-10-07 15:51:04
  • Java面向对象编程(封装/继承/多态)实例解析

    2023-11-11 11:33:09
  • C#实现Word转换TXT的方法详解

    2022-12-26 04:27:57
  • Kotlin Suspend挂起函数的使用详解

    2022-11-01 12:52:56
  • 在idea中显示springboot面板的方法

    2022-01-02 22:00:57
  • Android客户端与服务端数据加密传输方案详解

    2023-07-14 13:55:37
  • C# WebApi Get请求方式传递实体参数的方法示例

    2023-05-01 21:46:46
  • LRU缓存替换策略及C#实现方法分享

    2021-08-27 04:20:49
  • 保持Android Service在手机休眠后继续运行的方法

    2022-01-01 20:36:12
  • Java 8 中的 10 个特性总结及详解

    2023-07-21 00:06:51
  • HashSet如何保证元素不重复(面试必问)

    2023-04-12 02:16:24
  • 十分钟理解Java中的动态代理

    2022-05-16 04:53:19
  • Android实现授权访问网页的方法

    2022-05-13 15:39:57
  • Android在JNI中使用ByteBuffer的方法

    2021-11-08 21:14:35
  • WPF实现绘制扇形统计图的示例代码

    2021-11-29 23:42:00
  • 微信小程序 springboot后台如何获取用户的openid

    2023-01-13 17:07:42
  • 详解Eclipse提交项目到GitHub以及解决代码冲突

    2022-05-15 09:04:52
  • Java中this关键字的用法详解

    2023-10-04 05:05:53
  • asp之家 软件编程 m.aspxhome.com