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文件,并可以在其他的工程中使用它。
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的引用。
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次。在服务器应用程序的控制台窗口中,会看到类似的下图的窗口输出结果