创建动态WCF服务(无配置文件)

 public class WCFServer
{
ServiceHost host = null;
public WCFServer(string addressurl, string tcpurl,Type Servertype, Type IServertype)
{
host = new ServiceHost(Servertype, new Uri(addressurl));
host.AddServiceEndpoint(IServertype, new NetTcpBinding(), tcpurl);
host.AddServiceEndpoint(IServertype, new BasicHttpBinding(), addressurl);
//公布元数据
host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
} public void Start()
{
host.Open();
} public void Close()
{
host.Close();
}
}

核心类,定义了http 和tcp 两个协议传输通道

使用方法

 class Program
{
static void Main(string[] args)
{
StringBuilder addressurl = new StringBuilder();
addressurl.AppendFormat("http://{0}:{1}/{2}", "localhost", "", "HomeServer");
StringBuilder tcpurl = new StringBuilder();
tcpurl.AppendFormat("net.tcp://{0}:{1}/{2}", "localhost", "", "HomeServer");
WCFLibrary.WCFServer host = new WCFLibrary.WCFServer(addressurl.ToString(), tcpurl.ToString(),typeof(ServerModel.Server), typeof(ServerModel.IServer));
host.Start(); Console.WriteLine("服务已经开启。。。");
Console.Read();
}
}
 [ServiceContract]
[XmlSerializerFormat]
public interface IServer
{
[OperationContract]
string Print(string str);
}
   public class Server : IServer
{
public string Print(string str)
{
return str;
}
}

客户端调用方法

 class Program
{
static void Main(string[] args)
{
//ChannelFactory<ServerModel.IServer> factory = new ChannelFactory<ServerModel.IServer>(new NetTcpBinding(), "net.tcp://localhost:19011/HomeServer");
ChannelFactory<ServerModel.IServer> factory = new ChannelFactory<ServerModel.IServer>(new BasicHttpBinding(), "http://localhost:19010/HomeServer");
var channel = factory.CreateChannel();
var result = channel.Print("");
Console.WriteLine(result);
Console.ReadKey();
}
}

DEMO源码

链接:http://pan.baidu.com/s/1kVbbf1t 密码:i1x5

上一篇:百度地图SDK for Android v2.1.2全新发布


下一篇:HDU 5977 Garden of Eden (树分治+状态压缩)