1、配置文件启动与绑定
1.1、在host的app.config中配置服务的name behaviroConfiguration A B C 选项,host对server是添加引用,不是添加 服务引用。
<system.serviceModel>
<services>
<!--1-->
<service name="CCWorkbench.Server.Service1" behaviorConfiguration="behavior">
<host>
<baseAddresses>
<add baseAddress="http://10.76.37.152:5031/ser1"/>
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" contract="CCWorkbench.Server.IService1"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
1.2、在client中,需要是添加 服务引用,在app.config中自动生成引用数据。client中new对象即可调用。
2、程序启动与绑定
2.1、host对serve添加 引用,不修改app.config,然后在程序中如下写,在host open前,手动添加 A B C,启动服务。
namespace Server
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(ServiceLibrary.HelloWCF)))
{
host.AddServiceEndpoint(typeof(ServiceLibrary.IHelloWCF),
new NetTcpBinding(),
"net.tcp://localhost:9000/HelloWCF");
//下面的设置,允许在浏览器中查看。
ServiceMetadataBehavior metaBehavior = new ServiceMetadataBehavior();
metaBehavior.HttpGetEnabled = true;
metaBehavior.HttpGetUrl = new Uri("net.tcp://localhost:9000/HelloWCF");
host.Description.Behaviors.Add(metaBehavior);
host.Open();
Console.WriteLine("Please input exit to close host.");
string key = Console.ReadLine();
while (key.ToLower() != "exit")
{
Console.WriteLine("Please input exit to close host.");
key = Console.ReadLine();
}
}
}
}
}
2.2、在client中对server 添加 引用,不用修改app.config, 程序中如下:用ChannelFactory 创建对服务的绑定。
/// <summary>
/// 测试ServiceLibrary
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
ChannelFactory<ServiceLibrary.IHelloWCF> channelFactory =
new ChannelFactory<ServiceLibrary.IHelloWCF>(new NetTcpBinding());
ServiceLibrary.IHelloWCF client =
channelFactory.CreateChannel(new EndpointAddress("net.tcp://localhost:9000/HelloWCF"));
Console.WriteLine("------------Begin-------------");
Console.WriteLine(client.GetMessage("Hello WCF!"));
ServiceLibrary.Item item = new ServiceLibrary.Item(1);
item = client.TestDataContract(item);
Console.WriteLine("item.Id:" + item.Id);
Console.WriteLine("item.Name:" + item.Name);
Console.WriteLine("------------End---------------");
Console.ReadLine();
}
3、题外话
如果绑定服务的IP发生变化,则需要修改【net.tcp://localhost:9000/HelloWCF】的localhost部分,为了方便服务端服务器的切换可以把localhost改为域名,通过域名解析取代更改客户端绑定地址的目的。