一、代码结构:

二、数据实体类:

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. mybatis 学习五 二级缓存不推荐使用

    mybatis 二级缓存不推荐使用 一 mybatis的缓存使用. 大体就是首先根据你的sqlid,参数的信息自己算出一个key值,然后你查询的时候,会先把这个key值去缓存中找看有没有value,如 ...

  2. 517. Super Washing Machines

    ▶ 超级洗碗机.给定一个有 n 元素的整数数组,我们把 “将指定位置上元素的值减 1,同时其左侧或者右侧相邻元素的值加 1” 称为一次操作,每个回合内,可以选定任意 1 至 n 个位置进行独立的操作, ...

  3. bootstrap更新数据层

    mq推送数据,表格实时更新,发现销毁表格不太合适,整体表格闪动,于是选择更新数据层. 先初始化表格,然后在推送数据的时候先循环遍历数据 例如: initDevTable(data.operatingL ...

  4. 彻底禁止win10更新

    关闭win10自动更新: 可以用下面方法关闭: 1.首先在服务界面关闭Windows Update服务并设置为禁用并在恢复界面全部如下图设置为无操作. 2.只关闭了Windows Update服务发现 ...

  5. git_基本使用

    1.默认你已经安装了,git的客户端,这里我们使用git bash操作. 2.执行git init命令:     git ini 3.在本地创建ssh key: ssh-keygen -t rsa - ...

  6. HDFS NameNode HA 部署文档

    简介: HDFS High Availability Using the Quorum Journal Manager Hadoop 2.x 中,HDFS 组件有三个角色:NameNode.DataN ...

  7. 解决docker tty窗口太小,命令换行的问题

    docker exec -it -e LINES=$(tput lines) -e COLUMNS=$(tput cols) ed08 bash

  8. Java多线程同步方法

    一.同步方法 即有synchronized关键字修饰的方法. 由于java的每个对象都有一个内置锁,当用此关键字修饰方法时, 内置锁会保护整个方法.在调用该方法前,需要获得内置锁,否则就处于阻塞状态. ...

  9. Spring JMX之二:远程访问MBean

    虽然最初的JMX规范提及了通过MBean进行应用的远程管理,但是它并没有定义实际的远程 访问协议或API.因此,会由JMX供应商定义自己的JMX远程访问解决方案,但这通常又是专 有的. 为了满足以标准 ...

  10. Ansible常用模块命令

    Ansible常用模块命令 一.安装ansible yum install epel-release yum install ansible 二.配置文件配置 vi /etc/ansible/ansi ...