博客已迁到“金陵小周的技术博客”,博客园不在更新发表......

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

 1 public class WCFServer
 2     {
 3         ServiceHost host = null;
 4         public WCFServer(string addressurl, string tcpurl,Type Servertype, Type IServertype)
 5         {
 6             host = new ServiceHost(Servertype, new Uri(addressurl));
 7             host.AddServiceEndpoint(IServertype, new NetTcpBinding(), tcpurl);
 8             host.AddServiceEndpoint(IServertype, new BasicHttpBinding(), addressurl);
 9             //公布元数据
10             host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
11             host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
12         }
13 
14         public void Start()
15         {
16             host.Open();
17         }
18 
19         public void Close()
20         {
21             host.Close();
22         }
23     }

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

使用方法

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

 

客户端调用方法

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //ChannelFactory<ServerModel.IServer> factory = new ChannelFactory<ServerModel.IServer>(new NetTcpBinding(), "net.tcp://localhost:19011/HomeServer");
 6             ChannelFactory<ServerModel.IServer> factory = new ChannelFactory<ServerModel.IServer>(new BasicHttpBinding(), "http://localhost:19010/HomeServer");
 7             var channel = factory.CreateChannel();
 8             var result = channel.Print("12345");
 9             Console.WriteLine(result);
10             Console.ReadKey();
11         }
12     }

 

DEMO源码 

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

 

posted @ 2016-07-27 14:19  Pete-Jones  阅读(492)  评论(0编辑  收藏  举报

博客已迁到“金陵小周的技术博客”,博客园不在更新发表......