wcf 进程之间的通信,可以通过一个做为服务端和一个做为客户端实现通信
简单的服务端包括两部分:服务协定、服务的实现。
服务协定通过接口实现,定义了该服务执行的操作。
服务的实现就是继承接口,实现接口的操作。
服务协定接口:
[ServiceContract]
public interface IService
{
[OperationContract]
void Hello();
}
服务实现类:
[ServiceBehavior]
public class service:IService
{
public void Hello()
{
Console.WriteLine("hello");
}
}
至此服务端一些好,就一个简单的方法。
重要的就是配置文件的设置,vs2010 可以通过工具->wcf配置服务编辑器进行设置。服务端的设置如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="net.pipe://localhost/service" binding="netNamedPipeBinding"
bindingConfiguration="" contract="wcf_Service.IService" name="pipeClient"
kind="" endpointConfiguration="" />
</client>
<services>
<service name="wcf_Servicefg.service1">
<endpoint address="net.pipe://localhost/service" binding="netNamedPipeBinding"
bindingConfiguration="" name="pipeClient" contract="wcf_Service.IService" />
</service>
</services>
</system.serviceModel>
</configuration>
下面就是客户端的编写。要把服务器端配置文件拷到客户端(非常重要)。首先需要启动服务。
ServiceHost sh = new ServiceHost(typeof(service)); //service 是服务器端实现接口的service类。
sh.Open();
服务已经打开,下一步许建立服务器端和客户端之间的通道。
var binding = new NetNamedPipeBinding();
var address = new EndpointAddress("net.pipe://localhost/service");
var factory = new ChannelFactory<IService>(binding, address);
IService channel = factory.CreateChannel();
至此通道已建立,可以通过通道调用服务器端的方法,如下:
channel.Hello(); //hello()方法即是在服务器端定义的方法。
以上实现了一个进程调用另一个进程的方法,即进程之间的通信。