Wcf之四(代码创建服务及客户端)
简述
在开发WCF程序时,如何选择一个适合的绑定对于消息传输的可靠性,传输模式是否跨进程、主机、网络,传输模式的支持、安全性、性能等方面有着重要的影响。
这里列举些
绑定名称 | 用途描述 | 版本 |
basicHttpBinding | 支持基于WS-I Basic Profile 1.1规范的Web Service,主要支持早期的Web服务。 | 3.0/3.5 |
wsHttpBinding | 基于WS*的高级Web Service | 3.0/3.5 |
wsDualHttpBinding | 支持双工的Web Service | 3.0/3.5 |
webHttpBinding | 支持基于REST/POX的服务,使用XML和JSON序列化 | 3.0/3.5 |
netTcpBinding | .net程序间的通信,类似于.net Remoting技术 | 3.0/3.5 |
netNamedPipeBinding | 单个或多个.net系统间的本机通信 | 3.0/3.5 |
netMsmqBinding | 使用微软消息队列的异步通信 | 3.0/3.5 |
netTcpPeerBinding | 用于构建P2P网络应用程序的绑定 | 3.0/3.5 |
msmqIntegrationBinding | 通过使用MSMQ的队列对应用程序收发消息的绑定 | 3.0/3.5 |
wsFederationHttpBinding | 用于基于WS*的高级Web Service,使用统一身份验证 | 3.0/3.5 |
代码部署
服务端
接口实现(这里的接口和签名用的一样就不做重复了)这里通过winform形式部署
class ServiceFunction:ClassLibrary.myInterface
{
public string getServiceTime()
{
return DateTime.Now.ToString();
}
}
服务端的服务部署
ServiceHost host = null;
private void btnOpen_Click(object sender, EventArgs e)
{
host = new ServiceHost(typeof(WcfService2.ServiceFunction));//创建服务
//绑定协议
NetTcpBinding tcp=new NetTcpBinding();
//绑定地址
string address="net.tcp://localhost:3200/hello";
//端定义
host.AddServiceEndpoint(typeof(ClassLibrary.myInterface),tcp,address);
host.Opened += delegate{ lbState.Text = "服务开启";};
host.Open();
}
private void btnClose_Click(object sender, EventArgs e)
{
if (host.State != CommunicationState.Closed)
{
host.Close();
lbState.Text = "服务已经关闭";
}
}
客户端调用
服务启动后调用方法
NetTcpBinding bind = new NetTcpBinding();//绑定协议
EndpointAddress address = newEndpointAddress("net.tcp://localhost:3200/hello");//短点地址
ChannelFactory<ClassLibrary.myInterface> factory = newChannelFactory<myInterface>(bind,address);//工程通道
ClassLibrary.myInterface myObject=factory.CreateChannel();//创建服务方法
string servTime = myObject.getServiceTime();//调用服务方法
MessageBox.Show(servTime);
总结
这里使用代码发布服务和客户端代码。