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 = ;
wsHttp.MaxReceivedMessageSize = ;
wsHttp.ReaderQuotas.MaxArrayLength = ;
wsHttp.ReaderQuotas.MaxStringContentLength = ;
wsHttp.ReaderQuotas.MaxBytesPerRead = ;
wsHttp.ReaderQuotas.MaxDepth = ;
wsHttp.ReaderQuotas.MaxNameTableCharCount = ;
wsHttp.CloseTimeout = new TimeSpan(, , );
wsHttp.OpenTimeout = new TimeSpan(, , );
wsHttp.ReceiveTimeout = new TimeSpan(, , );
wsHttp.SendTimeout = new TimeSpan(, , );
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 = ; 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 = ;
wsHttp.MaxReceivedMessageSize = ;
wsHttp.ReaderQuotas.MaxArrayLength = ;
wsHttp.ReaderQuotas.MaxStringContentLength = ;
wsHttp.ReaderQuotas.MaxBytesPerRead = ;
wsHttp.ReaderQuotas.MaxDepth = ;
wsHttp.ReaderQuotas.MaxNameTableCharCount = ;
wsHttp.SendTimeout = new TimeSpan(, , );
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 = ;
}
}
} /// <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 = ;
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 = ;
if (double.TryParse(txtNum1.Text, out num1) && double.TryParse(txtNum2.Text, out num2))
{
DateTime dt = DateTime.Now;
BackWork.Run(() =>
{
for (int i = ; i < ; 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的更多相关文章
- Linux下进程间管道通信小作业
在进行这次作业之前,我们先来看看什么是管道吧! 管道是Linux中很重要的一种通信方式,是把一个程序的输出直接连接到另一个程序的输入,常说的管道多是指无名管道,无名管道只能用于具有亲缘关系的进程之间, ...
- 采用虚拟命名管道的字符设备和阻塞型I/O实现进程间的通信实现KWIC程序
采用虚拟命名管道的字符设备和阻塞型I/O实现进程间的通信实现KWIC程序专业程序代写c++程序代写
- c 进程间的通信
在上篇讲解了如何创建和调用进程 c 进程和系统调用 这篇文章就专门讲讲进程通信的问题 先来看一段下边的代码,这段代码的作用是根据关键字调用一个Python程序来检索RSS源,然后打开那个URL #in ...
- Unix系统中,两个进程间的通信
进程之间通常需要进行数据的传输或者共享资源等,因此进程间需要通讯. 可以通过管道,信号,消息队列,共享内存,信号量和套接字等方式 FIFO表示命名管道,这种管道的操作是基于先进先出原理. PIPE 表 ...
- python3,进程间的通信
本文来源于python 3.5版本的官方文档 multiprocessing模块为进程间通信提供了两种方法: 1.进程队列queue The Queue class is a near clone o ...
- python全栈开发day32-进程创建,进程同步,进程间的通信,进程池
一.内容总结 1.进程创建 1) Process:两种创建一个新进程的方法: 1.实例化Process,通过args=(,)元组形式传参,2创建类继承Process,类初始化的时候传参数 2) p.j ...
- Linux进程间的通信
一.管道 管道是Linux支持的最初Unix IPC形式之一,具有以下特点: A. 管道是半双工的,数据只能向一个方向流动: B. 需要双工通信时,需要建立起两个管道: C. 只能用于父子进程或者兄弟 ...
- Python 进程间的通信
#-*-coding:utf-8-*- '''python提供了多种进程间的通信方式,如:Queue,Pipe,Valie+Array等. Queue与Pipe的区别在于Pipe常用来在两个进程间通信 ...
- [Socket]Socket进程间的通信
转自:http://blog.csdn.net/giantpoplar/article/details/47657303 前面说到的进程间的通信,所通信的进程都是在同一台计算机上的,而使用socket ...
随机推荐
- thymeleaf 之 th:each迭代循环对象集合
thymeleaf 之 th:each迭代循环对象集合 2018年02月24日 14:32:31 阅读数:1382 th:each属性用于迭代循环,语法:th:each="obj,iterS ...
- Linux常用命令之-grep
简介 grep全称Global Regular Expression Print是一种强大的文本搜索工具,它能使用给定的正则表达式按行搜索文本输出,文件,目录等,统计并输出匹配的信息,grep在文本查 ...
- django-常用过滤器
django常用过滤器 add :字符串相加,数字相加,列表相加,如果失败,将会返回一个空字符串. default:提供一个默认值,在这个值被django认为是False的时候使用.比如:空字符串.N ...
- Request模块(八)
Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 “ ...
- django2.0实现数据详情页展示的流程
思路整理 1 先在urls.py中,定义路由获取的格式 url(r'^detail/(\d+)/$', views.blog_detail), 2 然后在views.py,定义数据获取的方法 def ...
- Linux内存地址映射
引言 看过原博主的一些文章,写得很好,虽然博主不提倡这种拿来主义,但我还是忍不住一时手痒.呵呵本文是针对32位x86 CPU中Linux内核地址映射过程的详细介绍和示例.其中由浅入深,介绍了相关寄存器 ...
- LinuxC编程怎么MakeFile
在linux下我们都知道可以利用命令gcc hello.c -o hello 命令来变异c语言程序.其中gcc hello.c -o hello中 hello是给这个编译后生成的可执行文件取个别名 再 ...
- 27-python 画图
绝佳教程:http://pyecharts.org/#/zh-cn/prepare?id=%E4%BD%BF%E7%94%A8%E4%B8%BB%E9%A2%98安装 pyecharts pip in ...
- [Training Video - 5] [Groovy Script Test Step - Collections, Exceptions] Array and ArrayList
Array: def x = new String[5] x[0] = "India" x[1] = "USA" x[2] = "Korea" ...
- 自动创建orcl表
using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Text; ...