一、代码结构:

二、数据实体类:

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的更多相关文章

  1. Linux下进程间管道通信小作业

    在进行这次作业之前,我们先来看看什么是管道吧! 管道是Linux中很重要的一种通信方式,是把一个程序的输出直接连接到另一个程序的输入,常说的管道多是指无名管道,无名管道只能用于具有亲缘关系的进程之间, ...

  2. 采用虚拟命名管道的字符设备和阻塞型I/O实现进程间的通信实现KWIC程序

    采用虚拟命名管道的字符设备和阻塞型I/O实现进程间的通信实现KWIC程序专业程序代写c++程序代写

  3. c 进程间的通信

    在上篇讲解了如何创建和调用进程 c 进程和系统调用 这篇文章就专门讲讲进程通信的问题 先来看一段下边的代码,这段代码的作用是根据关键字调用一个Python程序来检索RSS源,然后打开那个URL #in ...

  4. Unix系统中,两个进程间的通信

    进程之间通常需要进行数据的传输或者共享资源等,因此进程间需要通讯. 可以通过管道,信号,消息队列,共享内存,信号量和套接字等方式 FIFO表示命名管道,这种管道的操作是基于先进先出原理. PIPE 表 ...

  5. python3,进程间的通信

    本文来源于python 3.5版本的官方文档 multiprocessing模块为进程间通信提供了两种方法: 1.进程队列queue The Queue class is a near clone o ...

  6. python全栈开发day32-进程创建,进程同步,进程间的通信,进程池

    一.内容总结 1.进程创建 1) Process:两种创建一个新进程的方法: 1.实例化Process,通过args=(,)元组形式传参,2创建类继承Process,类初始化的时候传参数 2) p.j ...

  7. Linux进程间的通信

    一.管道 管道是Linux支持的最初Unix IPC形式之一,具有以下特点: A. 管道是半双工的,数据只能向一个方向流动: B. 需要双工通信时,需要建立起两个管道: C. 只能用于父子进程或者兄弟 ...

  8. Python 进程间的通信

    #-*-coding:utf-8-*- '''python提供了多种进程间的通信方式,如:Queue,Pipe,Valie+Array等. Queue与Pipe的区别在于Pipe常用来在两个进程间通信 ...

  9. [Socket]Socket进程间的通信

    转自:http://blog.csdn.net/giantpoplar/article/details/47657303 前面说到的进程间的通信,所通信的进程都是在同一台计算机上的,而使用socket ...

随机推荐

  1. SpringBoot入门篇--使用IDEA创建一个SpringBoot项目

    随着技术的更新对于开发速度的追求,我们越来越不能忍受的是Spring框架对于集成开发以后大量的配置问题.所以SprigBoot应运而生,SpringBoot框架其实就是在Spring框架的外边包裹上了 ...

  2. python爬搜狗微信获取指定微信公众号的文章

    前言: 之前收藏了一个叫微信公众号的文章爬取,里面用到的模块不错.然而 偏偏报错= =.果断自己写了一个 正文: 第一步爬取搜狗微信搜到的公众号: http://weixin.sogou.com/we ...

  3. 解决Linux下MySQL登录ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using passwor)问题

    两种方案: 一: 1.修改mysql配置文件:vim /etc/my.cnf 2.找到[mysqld]下添加 skip-grant-tables 配置 3.重启服务service mysqld res ...

  4. 部分流媒体协议及流媒体开发框架vitamio

    流媒体协议部分RTP.RTCP.RTSP.MMS.HLS.HTTP progressive streaming   流媒体协议:(RTP.RTCP.RTSP.MMS.HLS.HTTP progress ...

  5. pandas的数据结构

    要使用pandas,需要熟悉它的两个主要的数据结构,Series和DataFrame. Series series是一种类似于以为数组的对象,它由一组数据(各种numpy的数据类型)以及一组与之相关的 ...

  6. #用openfiledialog文件和savefileDialog打开和保存文件

    一.打开文件 Stream myStream = null;            OpenFileDialog openFileDialog1 = new OpenFileDialog();     ...

  7. MyEclipse编译报:javaScript Validator错误

    转自:https://blog.csdn.net/lkpmemory/article/details/8833329 Myeclipse编译报错如下: Errors occurred during t ...

  8. 学习 TCP 三次握手和四次挥手

    TCP三次握手和四次挥手的问题在面试中是最为常见的考点之一.很多读者都知道三次和四次,但是如果问深入一点,他们往往都无法作出准确回答. 本篇尝试使用动画来对这个知识点进行讲解,期望读者们可以更加简单地 ...

  9. shutdown和close的区别

    [shutdown和close的区别] 当所有的数据操作结束以后,你可以调用close()函数来释放该socket,从而停止在该socket上的任何数据操作:close(sockfd); 你也可以调用 ...

  10. 【读书笔记】《Python_Cookbook3》第一章:数据结构和算法

      Python提供了多样化有用的内建数据结构,例如列表.集合.字典.大多数时候,这些结构的使用比较简单,然后,一些关于搜索.排序.过滤的常见问题经常出现.本章节的目标是讨论常见的数据结构,以及涉及到 ...