昨晚买了本分布式程序设计,对Remoting比较关注。今天 忙了一整天,在调试Remoting ,搞的头昏脑涨. 现在把一些注意点列出来:
1。允许Remoting 访问的组件必须继承于 MarshalByRefObject类 如果客户端是基于接口的话,还必须定义相应的接口并实现(这里是ICustomer) public class Customer :MarshalByRefObject ,IRemotingBLL.ICustomer 2。服务端配置文件
<? xml version="1.0" encoding="utf-8" ?> < configuration > < system .runtime.remoting > < application > < service > < wellknown mode ="SingleCall" type="RemotingBLL.Customer, RemotingBLL" objectUri="Customer" /> < wellknown mode ="SingleCall" type="RemotingBLL.Order, RemotingBLL" objectUri ="Order" /> </ service > < channels > < channel ref ="Tcp Server" port ="6791" /> <!-- <channel type="System.Runtime.Remoting.Channels.Tcp.TcpServerChannel,System.Runtime.Remoting.Channels.Tcp" port="6791"></channel> --> </ channels > </ application > </ system.runtime.remoting > </ configuration >
其中<channel ref="Tcp Server"... 可以是<channel ref="http" ... 这样采用的是Http适合Internet, 通过以下语句启动服务端
private void frmServer_Load( object sender, EventArgs e) ... { RemotingConfiguration.Configure( " BLLServer.exe.config " , false ); // false 为不需要安全保证 }
客源户段的配置文件:
<? xml version="1.0" encoding="utf-8" ?> < configuration > < system .runtime.remoting > < application > < client > < wellknown type ="IRemotingBLL.ICustomer, IRemotingBLL" url ="tcp://localhost:6791/Customer" /> < wellknown type ="IRemotingBLL.IOrder, IRemotingBLL" url ="tcp://localhost:6791/Order" /> </ client > < channels > < channel ref ="Tcp Client" > < clientProviders > < formatter ref ="binary" /> </ clientProviders > </ channel > </ channels > </ application > </ system.runtime.remoting > </ configuration >
客户段的激活代码是 RemotingConfiguration.Configure("RemotingClient.exe.config",false); 简单的测试代码如下: 其中的Activator.GetObject(。。。方法的第一个参数为type 可以是接口(如果提供接口)或类 第2个为string 类型的 url 可以通过RemotingConfiguration.GetRegisteredWellKnownClientTypes()[i].ObjectUrl 获得
private void button1_Click( object sender, EventArgs e) ... { IRemotingBLL.ICustomer customer = (IRemotingBLL.ICustomer)Activator.GetObject( typeof (IRemotingBLL.ICustomer), RemotingConfiguration.GetRegisteredWellKnownClientTypes()[ 0 ].ObjectUrl); IRemotingBLL.IOrder order = (IRemotingBLL.IOrder)Activator.GetObject( typeof (IRemotingBLL.IOrder), RemotingConfiguration.GetRegisteredWellKnownClientTypes()[ 1 ].ObjectUrl); MessageBox.Show(customer.GetCustomer( " Hello Server! " ) ); MessageBox.Show(order.GetOrder( 58 )); }