remoting的三元素:远程对象,宿主程序(服务器程序),客户端程序;
远程对象代码:
using System;
namespace RemoteObject
{
public class MyObject:MarshalByRefObject
{
public string SayHello()
{
Console.WriteLine("Hello EveryOne");
return "HelloEveryOne";
}
public void ShowDomain()
{
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
}
}
}
远程对象的激活方式分为客户端激活类型的和服务器端激活的两种;
1、客户端激活:不管是对象的创建还是对象方法的执行都是在服务器端,服务器为每个客户创建一个对象实例,并且在租约时间到期并且垃圾回收器发挥作用之前对象将一直处于激活状态,客户端可以从远程获取方法的返回值;
1.1 硬编码(在配置文件中注册将要被激活的远程对象)
服务器端配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.remoting>
<application>
<service>
<activated type="RemoteObject.MyObject,RemoteObject"/>
</service>
<channels>
<channel ref="tcp" port="9090"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
服务器端代码:
using System;
using System.Runtime.Remoting;
namespace MyServer>/p>
{ class Program
{
static void Main(string[] args)
{
RemotingConfiguration.Configure("MyServer.exe.config");
Console.ReadLine();
}
}
}
客户端配置文件:
<?xml version="1.0" encoding="utf-8" ?><configuration>
<system.runtime.remoting>
<application>
<client url="tcp://localhost:9090">
<activated type="RemoteObject.MyObject,RemoteObject"/>
</client>
<channels>
<channel ref="tcp" port="0"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
客户端代码:
using System.Runtime.Remoting;
using RemoteObject;
namespace MyClient
{
class Program
{
static void Main(string[] args)
{
RemotingConfiguration.Configure("MyClient.exe.config");
MyObject m = new MyObject();
m.ShowDomain();
Console .WriteLine ( m.SayHello());
Console.ReadLine();
}
}
}