为了简单明了我只建了一个控制台程序将服务端跟调用的客户端写在了一起
1.建立服务端接口并实现接口
[ServiceContract]
interface ITTest
{
[OperationContract]
string Test();
}
class TTest : ITTest
{
public string Test()
{
return "Service : OK";
}
}
2.动态生成服务端并调用
static void Main(string[] args)
{
//生成服务端
Uri HttpAddress = new Uri("http://localhost:8001");
Uri TcpAddress = new Uri("net.tcp://localhost:8002");
ServiceHost _ServiceHost = new ServiceHost(typeof(TTest), HttpAddress, TcpAddress);
_ServiceHost.AddServiceEndpoint(typeof(ITTest), new BasicHttpBinding(), "http://localhost:8001");
_ServiceHost.AddServiceEndpoint(typeof(ITTest), new NetTcpBinding(), "net.tcp://localhost:8002");
ServiceMetadataBehavior _ServiceMetadataBehavior = new ServiceMetadataBehavior();
_ServiceMetadataBehavior.HttpGetEnabled = true;
_ServiceMetadataBehavior.HttpGetUrl = new Uri("http://localhost:8001");
_ServiceHost.Description.Behaviors.Add(_ServiceMetadataBehavior);
_ServiceHost.Open();
Console.WriteLine("Service : Open");
Console.ReadLine();
//调用服务端(http,tcp)
ITTest HttpProxy = ChannelFactory<ITTest>.CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8001"));
Console.WriteLine(HttpProxy.Test());
ITTest TcpProxy = ChannelFactory<ITTest>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8002"));
Console.WriteLine(TcpProxy.Test());
Console.ReadLine();
_ServiceHost.Close();
}
其实上面动态生成的服务端也可以在 配置文件 app.config中实现
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="ConsoleApplication1.TTest" behaviorConfiguration="MyServiceTypeBehaviors">
<host>
<baseAddresses>
<add baseAddress=">
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings />
<client />
</system.serviceModel>
</configuration>