工程结构:
注意三个项目都需要引用System.ServiceModel以及System.Runtime.Serialization。
CommonLib工程:
1 [ServiceContract]//, ServiceKnownType(typeof(User))] 2 public interface IMyObject 3 { 4 [OperationContract] 5 int Add(int x, int y); 6 [OperationContract]//, ServiceKnownType(typeof(User))] 7 User GetInstance(); 8 }
IMyObject
WCF接口需要添加ServiceContract特性,方法需要添加OperationContract。
User类是需要传输的数据类型
1 [DataContract] 2 public class User 3 { 4 private string _name; 5 private int _age; 6 public User(string name, int age) 7 { 8 _name = name; 9 _age = age; 10 } 11 [DataMember] 12 public string Name 13 { 14 get { return _name; } 15 set { _name = value; } 16 } 17 [DataMember] 18 public int Age 19 { 20 get { return _age; } 21 set { _age = value; } 22 } 23 }
User.cs
类特性添加DataContract,需要暴露的属性添加特性:DataMember,注意属性需要实现Get,Set方法,缺一不可。
Server工程:
1 [ServiceBehaviorAttribute(IncludeExceptionDetailInFaults = true)] 2 class MyObject:IMyObject 3 { 4 User _student; 5 public int Add(int x, int y) 6 { 7 return x + y; 8 } 9 10 public User GetInstance() 11 { 12 if (_student == null) 13 _student = new User("Jashon Han", 26); 14 return _student; 15 } 16 }
MyObject.cs
IMyObject接口的实现。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 try 6 { 7 Console.WriteLine("Start my service!"); 8 Uri baseAddress = new Uri("net.tcp://localhost:8011/MyService"); 9 ServiceHost host = new ServiceHost(typeof(MyObject), baseAddress); 10 11 ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); 12 13 host.Description.Behaviors.Add(smb); 14 15 host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); 16 host.AddServiceEndpoint(typeof(IMyObject), new NetTcpBinding() { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxArrayLength = 2147483647 } }, baseAddress); 17 18 host.Open(); 19 Console.WriteLine("The service is ready."); 20 Console.WriteLine("Press <ENTER> to terminate service."); 21 Console.WriteLine(); 22 } 23 catch (Exception ex) 24 { Console.WriteLine(ex); } 25 26 Console.ReadLine(); 27 28 } 29 }
Program.cs
MaxReceivedMessageSize属性和MaxArrayLength是设定传输数据大小,如果没有特别需求,默认就好。
Client 工程:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding() { MaxReceivedMessageSize = 2147483647 }; 6 binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxArrayLength = 2147483647 }; 7 System.ServiceModel.ChannelFactory<IMyObject> factory = new System.ServiceModel.ChannelFactory<IMyObject>(binding, new System.ServiceModel.EndpointAddress("net.tcp://localhost:8011/MyService")); 8 IMyObject test = factory.CreateChannel(); 9 var result = test.Add(12, 13); 10 var student = test.GetInstance(); 11 Console.WriteLine("Student Name:{0},Age{1}", student.Name, student.Age); 12 Console.WriteLine(result); 13 Console.ReadKey(); 14 15 } 16 }
Program.cs
以上服务的绑定等操作都是通过代码实现,也可以通过配置文件实现。
时间: 2024-09-29 18:08:01