您的位置:首页 > 其它

如何实现一个简单的remoteing实例

2005-12-22 18:16 766 查看
我们先花20分钟做一个简单的remoteing的例子。
首先我们建立一个dll的remoteing远程对象,这个对象有点类似于EJB里面的接口文件的功能,但是又不完全只是负责通讯,我们会把业务逻辑也写在这个接口里面:
建立1个类库项目RemoteObject:
using System;
namespace RemoteObject
{
public class MyObject:MarshalByRefObject
{
public int Add(int a,int b)
{
return a+b;
}
public string str()
{
return "i am come from server:";
}
}
}
编译一下。
接着建立服务器端程序RemoteServer:
using System;
using System.Runtime.Remoting;
namespace RemoteServer
{
class MyServer
{
[STAThread]
static void Main(string[] args)
{
RemotingConfiguration.Configure("RemoteServer.exe.config");
Console.ReadLine();
}
}
}
并添加一个配置文件App.config:
<configuration>
<system.runtime.remoting>
<application name="RemoteServer">
<service>
<wellknown type="RemoteObject.MyObject,RemoteObject" objectUri="RemoteObject.MyObject"
mode="Singleton" />
</service>
<channels>
<channel ref="tcp" port="9999"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
将刚才编译好的dll文件考到新建的服务器程序的bin目录下,添加引用,编译服务器程序。
建立客户端程序RemoteClient:
using System;
namespace RemoteClient
{
class MyClient
{
[STAThread]
static void Main(string[] args)
{
RemoteObject.MyObject remoteclient = (RemoteObject.MyObject)Activator.GetObject(typeof(RemoteObject.MyObject),System.Configuration.ConfigurationSettings.AppSettings["ServiceURL"]);
Console.WriteLine(remoteclient.str()+remoteclient.Add(1,2));
Console.ReadLine();
}
}
}
建立客户端程序的配置文件App.config:
<configuration>
<appSettings>
<add key="ServiceURL" value="tcp://localhost:9999/RemoteObject.MyObject"/>
</appSettings>
</configuration>
将刚才编译好的dll文件考到新建的客户端程序的bin目录下,添加引用,编译服务器程序。
先运行服务器程序,然后在运行客户端程序,可以看到如下界面:



现在我们完成了一个简单的remoteing实例,他和EJB同样是实现异地通讯,但是我们现在看看他和EJB有什么不同:
1.remoteing事务写在dll(即接口),ejb写在服务器。
2.服务器程序相当于EJB里面的容器,可以装载N个实现业务的接口,通过对配置文件里面的通道类型,端口号,接口名字的设置,确定客户端程序访问哪一个dll.
3.通过客户段激活和服务器激活的例子也可以知道,虽然完成的业务是在dll里面写好了,但实际上申请的空间和业务所使用的内存空间是在服务器里面,dll对象会通过自己的构造函数去使用服务器程序在服务器端构造一些内存地址,以及存放变量或者其他函数的空间,所以dll的业务操作并不是在客户端。
所以由此也可知道,实现事务所在的内存地址实际上是在服务器上面。
(感谢lovecherry的blog,我的文章里面加入了一些自己的理解和思考,如果大家想看到纯净版的remoting请看http://www.cnblogs.com/lovecherry,不敢掠人之美。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐