.NET Remoting Basic(1)-概览
2010-08-26 22:27 Clingingboy 阅读(496) 评论(0) 编辑 收藏 举报.net Remoting是一个.net体系下的分布式架构. 以Advantages of .NET Remoting 为范本来学习下.
一.定义公用接口和对象
1.接口
public interface ICustomerManager { Customer GetCustomer(int id); }
2.对象
注意此对象被标记为可序列化
[Serializable] public class Customer { public String FirstName; public String LastName; public DateTime DateOfBirth; public Customer() { Console.WriteLine("Customer.constructor: Object created"); } public int GetAge() { Console.WriteLine("Customer.getAge(): Calculating age of {0}, " + "born on {1}.", FirstName, DateOfBirth.ToShortDateString()); TimeSpan tmp = DateTime.Today.Subtract(DateOfBirth); return tmp.Days / 365; // rough estimation } }
二.注册服务器端服务
1.定义可跨应用程序域边界的类型
当跨应用程序域边界使用类型时,类型必须是从 MarshalByRefObject 继承的
class CustomerManager: MarshalByRefObject, ICustomerManager { public CustomerManager() { Console.WriteLine("CustomerManager.constructor: Object created"); } public Customer GetCustomer(int id) { Console.WriteLine("CustomerManager.getCustomer): Called"); Customer tmp = new Customer(); tmp.FirstName = "John"; tmp.LastName = "Doe"; tmp.DateOfBirth = new DateTime(1970,7,4); Console.WriteLine("CustomerManager.getCustomer(): Returning " + "Customer-Object"); return tmp; } }
class ServerStartup { static void Main(string[] args) { Console.WriteLine ("ServerStartup.Main(): Server started"); HttpChannel chnl = new HttpChannel(1234); ChannelServices.RegisterChannel(chnl); RemotingConfiguration.RegisterWellKnownServiceType( typeof(CustomerManager), "CustomerManager.soap", WellKnownObjectMode.Singleton); // the server will keep running until keypress. Console.ReadLine(); } }
3.客户端调用
static void Main(string[] args) { HttpChannel channel = new HttpChannel(); ChannelServices.RegisterChannel(channel); ICustomerManager mgr = (ICustomerManager) Activator.GetObject( typeof(ICustomerManager), "http://localhost:1234/CustomerManager.soap"); Console.WriteLine("Client.Main(): Reference to CustomerManager acquired"); Customer cust = mgr.GetCustomer(4711); int age = cust.GetAge(); Console.WriteLine("Client.Main(): Customer {0} {1} is {2} years old.", cust.FirstName, cust.LastName, age); Console.ReadLine(); }