.Net Remoting 实例 - 中国WEB开发者网络 (http://www.webasp.net) -- 技术教程 (http://www.webasp.net/article/) --- .Net Remoting 实例 (http://www.webasp.net/article/25/24213.htm) |
| -- 作者:未知 -- 发布日期: 2005-05-17 |
先简要地讨论远程对象和一个简单的客户机/服务器应用程序,该程序使用了远程对象。执行的远程对象是Hello。 HelloServers是服务器上应用程序的主类,HelloClient是客户上应用程序的主类,如下图所示: 第一步:创建远程的共享库 为了说明.NET Remoting 是如何运行的,先创建一个简单的类库,以创建远程的对象。 依次点击“文件”->“新创建”->“工程”,选择创建一个C# Library,并将其命名为RemoteHello,然后点击OK按钮。这将创建一个.NET Remote客户端和服务器端用来通讯的“共享命令集”。 程序集的名称是RemoteHello.dll,类的名称是Hello, 类Hello是从 System.MarshallByRefObject 派生出来的。 程序集的完整代码 Hello.cs为: using System; namespace Wrox.ProCSharp.Remoting { /// <summary> /// Class1 的摘要说明。 /// </summary> public class Hello : System.MarshalByRefObject { public Hello() { // // TODO: 在此处添加构造函数逻辑 // Console.WriteLine("Constructor called"); } ~Hello() { Console.WriteLine("Destructor called"); } public string Greeting(string name) { Console.WriteLine("Greeting called"); return "Hello," + name; } } } 编译创建的工程,就会得到一个DLL文件,并可以在其他的工程中使用它。 第二步:创建简单的服务器 创建一个C#控制台应用程序HelloServer 。 为了使用TcpServerChannel类,必须引用 System.Runtime.Remoting程序集,另外更重要的是,引用上面创建的RemoteHello程序集。 在Main()方法中,用端口号8086创建一个 System.Runtime.Channels.Tcp信道,该信道 使用System.Runtiem.Remoting.Channels.ChannelServices注册,使之用于远程对象。 在远程对象注册之后,使服务器一直处于运行状态,直到按任意键为止: HelloServer.cs的完整代码为: using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Wrox.ProCharp.Remoting { public class HelloServer { [STAThread] public static void Main(string[] args) { TcpServerChannel channel = new TcpServerChannel(8086); ChannelServices.RegisterChanel(channel); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Hello),"Hi", WellKnownObjectMode.SingleCall); System.Console.WriteLine("hit to exit"); System.Console.ReadLine(); } } } 名字空间是对象所需要的。请记住,如果得到System.Runtime.Remoting.Channels.Tcp名字空间不存在的信息,请检查是否象上面的代码那样添加了对System.Runtime.Remoting.dll的引用。 第三步: 创建简单的客户机 客户机也是一个C#控制台应用程序 HelloClient. 这里也引用了System.Runtime.Remoting 程序集,以便使用TcpClientChannel类。 此外,也必须引用RemoteHello程序集。 在客户机程序中,要创建一个TcpClientChannel对象,这个对象注册在ChannelServices 中。 对于TcpChannel,使用默认的构造函数,因此可以选择任意一个端口。接下来使用Activator类把代理对象返回给远程对象。 HelloClient.cs 的完整代码为: using System; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Wrox.ProCSharp.Remoting { /// <summary> /// HelloClient 的摘要说明。 /// </summary> public class HelloClient { [STAThread] public static void Main(string[] args) { ChannelServices.RegisterChannel(new TcpClientChannel()); Hello obj = (Hello)Activator.GetObject(typeof(Hello),"tcp://localhost:8086/Hi"); if (obj == null) { Console.WriteLine("could not locate server"); return; } for(int i=0;i<5; i++) { Console.WriteLine(obj.Greeting("Christian")); } } } } 当打开服务器和客户机程序Hello时,Christian在客户控制中会出现5次。在服务器应用程序的控制台窗口中,会看到类似的下图的窗口输出结果 |
| webasp.net |