remoting实例

来源:互联网 发布:二手车价格计算器软件 编辑:程序博客网 时间:2024/06/02 16:20
1.App.config文件内容:定义remoting通信通道与服务程序
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
<system.runtime.remoting>
        
<application>
            
<channels>
                
<channel ref="http" port="8080">
                    
<serverProviders>
                        
<formatter ref="binary" typeFilterLevel="Full" />
                        
<formatter ref="soap" typeFilterLevel="Full" />
                    
</serverProviders>
                
</channel>
                
<channel ref="tcp" port="9999">
                    
<serverProviders>
                        
<formatter ref="binary" typeFilterLevel="Full" />
                        
<formatter ref="soap" typeFilterLevel="Full" />
                    
</serverProviders>
                
</channel>
            
</channels>
            
<service>
                
<wellknown mode="Singleton"
注意:服务端使用这条 type
="RemoteLib.RemoteObject, RemoteLib" //定义服务端程序               客户端使用这条 type="RemoteInterface.IRemote, RemoteInterface" //定义客户端程序
上面两条代码写在一起是为了便于理解,实际要分开定义到各自的App.config文件中去,其它代码不变.
                  objectUri
="remoteobj" />
                  
<!--<activated  type="RemoteLib.RemoteObject,RemoteLib"></activated>-->
            
</service>
        
</application>
    
</system.runtime.remoting>
</configuration>

2.在宿主程序中(如winForm,service)启动remoting通信服务:
System.Runtime.Remoting.RemotingConfiguration.Configure(@"C:Program FileswindowsremotingWindowsServiceRemoting.exe.config", false);

3.在客户端程序中(如winForm,web)启动remoting通信服务:
System.Runtime.Remoting.RemotingConfiguration.Configure(Application.StartupPath + "/RemoteHost.exe.config");

4.在客户端中通过Activator来创建接口对象,之后就利用其对象做各种调用工作;
private IRemote getCurrentRemote()
{
   if (this.remote == null)
   {
      this.remote = Activator.GetObject(typeof(IRemote), "tcp://202.0.0.122:9999/remoteobj") as IRemote;
   }
   return this.remote;
}

注:项目文件中的命名空间不要轻易改变,最好是和项目名保持一致(即默认名)。否则容易出现布署时“无法加载数据文件或程序集….”等等诸如此类的消息出来。RemoteObject是从IRemote继承下来的具体实现类,它实现时要在类前加上可序列化标识 [Serializable()]
在编写服务器端程序时,最好将DLL文件通过”项目引用”的方式添加到宿主程序中去,并检查项目依赖项是否正确,在编写客户端程序时,采用”浏览引用”添加接口DLL文件。

RemoteInterface和RemoteLib是命名空间。IRemote是接口(interface),RemoteObject是从IRemote继承下来的具体实现类。在服务端使用的是实现类RemoteObject, 在客户端使用的是接口IRemote.