c# wcf NetNamePipeBinding 实现同一系统上不同进程之间的通信

本文详细介绍了如何使用WCF实现进程间的通信,包括服务端与客户端的搭建,配置文件设置,以及关键代码解析。通过实例展示了如何创建简单服务端与客户端,以及通道建立与方法调用的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()方法即是在服务器端定义的方法。

以上实现了一个进程调用另一个进程的方法,即进程之间的通信。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值