项目一:类库项目。定义服务,code实现服务接口的类。[如上图的Service]
namespace CodesContract
{
[ServiceContract(Name = "CodeService", Namespace = "http://www.rxm.net")]
public interface ICodeContract
{
[OperationContract]
string GetName(string name);
}
public class CodeContract : ICodeContract
{
#region ICodeContract 成员
public string GetName(string name)
{
return "My name is " + name;
}
#endregion
}
}
项目二:控制台项目。服务寄宿的宿主,公布终结点。[如上图ServideHost,ABC]
namespace CodesHost
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(CodesContract.CodeContract)))
{
host.AddServiceEndpoint(typeof(CodesContract.ICodeContract), new NetTcpBinding(), "net.Tcp://localhost:806/CodesName");
host.Open();
Console.Read();
}
}
}
}
项目三:控制台项目。定义与服务端相同的服务,终结点地址要与服务终结点地址和通信协议相同。[如上图左边]
namespace CodesClient
{
[ServiceContract(Name = "CodeService", Namespace = "http://www.rxm.net")]
public interface ICodeContract
{
[OperationContract]
string GetName(string name);
}
class Program
{
static void Main(string[] args)
{
ICodeContract proxy = ChannelFactory<ICodeContract>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.Tcp://localhost:806/CodesName"));
string name = proxy.GetName("rxm");
Console.WriteLine(name);
Console.ReadKey();
}
}
}