.Net Remoting 实例

先简要地讨论远程对象和一个简单的客户机 / 服务器应用程序,该程序使用了远程对象。执行的远程对象是 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

{

///

1<summary>
2
3///  Class1 的摘要说明。 
4
5///  </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

{

///

1<summary>
2
3///  HelloClient 的摘要说明。 
4
5///  </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次。在服务器应用程序的控制台窗口中,会看到类似的下图的窗口输出结果

Published At
Categories with Web编程
Tagged with
comments powered by Disqus