本节的主要内容:1、通过代理类的方式调用服务操作。2、通过通道的方式调用服务操作。3、代码下载
一、通过代理类的方式调用服务操作(两种方式添加代理类)
1.手动编写代理类,如下:
客户端契约:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.ServiceModel;
namespace y.WcfFirst.Client.Proxys
{
[ServiceContract]
public interface IHello
{
[OperationContract]
string Say(string name);
}
}
客户端代理类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.ServiceModel;
using System.ServiceModel.Channels;
namespace y.WcfFirst.Client.Proxys
{
public class HelloProxy:ClientBase<IHello>,IHello
{
public HelloProxy()
: base()
{
} public string Say(string name)
{
return base.Channel.Say(name);
}
}
}
客户端app.config文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint name="wcfFirst"
address="net.tcp://localhost:6666/hello"
binding="netTcpBinding"
contract="y.WcfFirst.Client.Proxys.IHello"></endpoint>
</client>
</system.serviceModel>
</configuration>
客户端的调用:
using (HelloProxy proxy = new HelloProxy())
{
Console.WriteLine("Recevie from Server:{0}", proxy.Say(name));
proxy.Close();
}
2.通过Metadata方式产生代理类。
服务端需要对app.config进行配置如下:
客户端的操作步骤:先运行服务端(host)。
a.在客户端点击Add Service Reference按钮,添加Service引用。如下图:
b.输入Address地址:http://localhost:8888,点击"GO",获取服务操作。并且重命名Namespace,如下图:
c.客户端对代理类的调用。
using (HelloClient clientProxy = new HelloClient())
{
Console.WriteLine("Recevie from Server:{0}", clientProxy.Say(name));
clientProxy.Close();
}
二、通过通道方式调用服务操作
1.客户端契约,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.ServiceModel;
namespace y.WcfFirst.ClientChannel.Proxy
{
[ServiceContract]
public interface IHello
{
[OperationContract]
string Say(string name);
}
}
2.客户端配置文件的设置:如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint name="wcfFirst"
address="net.tcp://localhost:6666/hello"
binding="netTcpBinding"
contract="y.WcfFirst.ClientChannel.Proxy.IHello"></endpoint>
</client>
</system.serviceModel>
</configuration>
3.客户端调用服务操作:如下:
ChannelFactory<IHello> factory = new ChannelFactory<IHello>("wcfFirst");
IHello channelProxy = factory.CreateChannel();
using(channelProxy as IDisposable)
{
Console.WriteLine("Recevie from Server:{0}", channelProxy.Say(name));
}