近日在研究WCF,现将成功过的代码贴出来。
一、服务端代码:
Uri wcfUri = new Uri("http://10.68.198.41:8001/WCF/");
ServiceHost serviceHost = new ServiceHost(typeof(Service1), wcfUri);
//支持NetTcpBinding
NetTcpBinding netTcpBind = new NetTcpBinding();
netTcpBind.Security.Mode = SecurityMode.None;
netTcpBind.MaxBufferPoolSize = Int32.MaxValue;
netTcpBind.MaxBufferSize = Int32.MaxValue;
netTcpBind.MaxConnections = Int16.MaxValue;
netTcpBind.MaxReceivedMessageSize = Int32.MaxValue;
//支持WSHttpBinding
WSHttpBinding wsHttpBind = new WSHttpBinding();
wsHttpBind.Security.Mode = SecurityMode.None;
wsHttpBind.MaxReceivedMessageSize = Int32.MaxValue;
wsHttpBind.MaxBufferPoolSize = Int32.MaxValue;
wsHttpBind.AllowCookies = true;
//元数据地址
ServiceMetadataBehavior metadata = new ServiceMetadataBehavior();
metadata.HttpGetEnabled = true;
metadata.HttpGetUrl = new Uri("http://10.68.198.41:8001/mex");
serviceHost.AddServiceEndpoint(typeof(IService1), wsHttpBind, "WCFServer");
serviceHost.Description.Behaviors.Add(metadata);
serviceHost.Open();
二、客户端连接代码:首先要引用这个服务,同时要注意一下引用后的命名空间。如“using NewsRemindWinApp.ServiceReference1;”
//方式1:不用配置XML
//EndpointAddress address = new EndpointAddress("http://10.66.237.118:8001/WCF/WCFServer");
//WSHttpBinding wsHttpBind = new WSHttpBinding();
//wsHttpBind.Security.Mode = SecurityMode.None;
//wsHttpBind.MaxReceivedMessageSize = Int32.MaxValue;
//wsHttpBind.MaxBufferPoolSize = Int32.MaxValue;
//wsHttpBind.AllowCookies = true;
//ChannelFactory<IService1> factory = new ChannelFactory<IService1>(wsHttpBind, address);
//IService1 channel = factory.CreateChannel();
//MSGContract msg = new MSGContract();
//msg.MsgReceiver = "test";
//msg.MsgTitle = "WCF消息测试";
//msg.MESSAGES = "能看到就表示OK了";
//channel.SendMSG(msg);
//方式2:从config文件中直接利用
Service1Client client = new Service1Client();
MSGContract msg1 = new MSGContract();
msg1.MsgReceiver = "test";
msg1.MsgTitle = "WCF消息测试";
msg1.MESSAGES = "能看到就表示OK了";
client.SendMSG(msg1);