首页 > 代码库 > 不引用服务使用WCF,编写客户端代理类

不引用服务使用WCF,编写客户端代理类

首先在解决方案中新建一个类库TestService.cs 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceModel;namespace WCFService{    [ServiceContract]    public interface IHelloWCFService    {        [OperationContract]        string HelloWCF();    }    public class HelloWCFService : IHelloWCFService    {        public string HelloWCF()        {            return "Hello WCF!";        }    }    class TestService    {    }}

  然后编译一下,这样在bin文件夹就会有一个WCFService.dll动态链接库

2.在HelloWCFService中引用WCFService.dll

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceModel;namespace HelloWCFService{    class Program    {        static void Main(string[] args)        {            ServiceHost host = new ServiceHost(typeof(WCFService.HelloWCFService));            WSHttpBinding httpBinding = new WSHttpBinding(SecurityMode.None);            host.AddServiceEndpoint(typeof(WCFService.IHelloWCFService), httpBinding, "http://localhost:2589/");            host.Open();            Console.WriteLine("服务已启动");            Console.Read();            host.Close();        }    }   }

3.此时从服务端启动服务即可。

至此,服务端工作到此结束,当然了,这不是在IIS上部署,而是使用控制台启动服务的。

接下来就是客户端代理了,

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.ServiceModel;using WCFService;namespace FiveWCFClient{    class Program    {        static void Main(string[] args)        {            EndpointAddress remoteAddress = new EndpointAddress("http://localhost:2589/");            HelloWCFClient client = new HelloWCFClient(new WSHttpBinding(SecurityMode.None), remoteAddress);            string result = client.HelloWCF();            client.Close();            Console.WriteLine(result);            Console.ReadLine();        }    }    public class HelloWCFClient : ClientBase<IHelloWCFService>, IHelloWCFService    {        public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)            : base(binding, remoteAddress)        { }        public string HelloWCF()        {            return base.Channel.HelloWCF();        }    }}

这是启动客户端,将会返回服务端方法的返回值。

不引用服务使用WCF,编写客户端代理类