定义服务契约-创建宿主程序-创建客户端程序访问服务 namespace HelloService{ ////// 服务契约 /// [ServiceContract] public interface IHelloService { ////// 服务操作 /// /// ///[OperationContract] string SayHello(string name); }}
类HelloService继承接口IHelloService
namespace HelloService{ public class HelloService:IHelloService { ////// 打招呼 /// /// ///public string SayHello(string name) { return name + ":say hello!"; } }}
定义一个客户端
namespace HelloClient{ class Program { static void Main(string[] args) { using (HelloProxy proxy=new HelloProxy()) { Console.WriteLine(proxy.Say("KAKA")); Console.Read(); } } } ////// 硬编码服务契约 /// interface IService { ////// 服务操作 /// /// ///[OperationContract] string Say(string name); } /// /// 客户端代理类型 /// class HelloProxy : ClientBase, IService { /// /// 硬编码定义绑定 /// public static readonly Binding HelloBinding = new NetNamedPipeBinding(); public static readonly EndpointAddress HelloAddress = new EndpointAddress(new Uri("net.pipe://localhost/Hello")); public HelloProxy() : base(HelloBinding, HelloAddress) { } public string Say(string name) { //使用Channel属性对服务进行调用 return Channel.SayHello(name); } }}
宿主程序
namespace HelloServiceHost{ class Program { static void Main(string[] args) { using (MyHelloHost host=new MyHelloHost()) { host.Open(); Console.Read(); } } } public class MyHelloHost:IDisposable { ////// 定义一个服务对象 /// private ServiceHost _myHost; public ServiceHost MyHost { get { return _myHost; } set { _myHost = value; } } ////// 定义一个基地址 /// public const string BaseAddress = "net.pipe://localhost"; ////// 可选地址 /// public const string HelloServiceAddress = "Hello"; ////// 服务契约实现类型 /// public static readonly Type ServiceType=typeof(HelloService.HelloService); ////// 服务契约接口 /// public static readonly Type ContractType=typeof(HelloService.IHelloService); ////// 服务定义一个绑定 /// public static readonly Binding helloBinding = new NetNamedPipeBinding(); ////// 构造服务对象 /// protected void CreateHelloService() { //创建服务对象 _myHost = new ServiceHost(ServiceType, new Uri[] { new Uri(BaseAddress)}); //给当前数组对象添加终结点 _myHost.AddServiceEndpoint(ContractType, helloBinding, HelloServiceAddress); } ////// 打开服务 /// public void Open() { Console.WriteLine("开始启动服务!"); _myHost.Open(); Console.WriteLine("服务已经启动!"); } ////// 构造方法 /// public MyHelloHost() { CreateHelloService(); } ////// 销毁对象 /// public void Dispose() { if (_myHost!=null) { (_myHost as IDisposable).Dispose(); } } }}
要先启动服务HelloServiceHost
再启动客户端