1、创建一个远程对象(DLL):新建一个解决方案(类库),命名为RemoteObject
创建一个类 RemoteTest,代码如下
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Data;
usingSystem.Data.SqlClient;
namespaceRemoteObject
{
publicclassRemoteTest : System.MarshalByRefObject//这是不能少的
{
SqlConnectioncon;
DataSetds;
SqlDataAdapterda;
stringconStr = "data source=HEYU\\SQLEXPRESS;initial catalog=schooldatabase;integrated security=SSPI;persist security info=False;packet size=4096";
stringqueryStr = "select * from book";
publicDataTabledatable()
{
using (con = newSqlConnection(conStr))
{
using (da = newSqlDataAdapter(queryStr, con))
{
ds = newDataSet();
da.Fill(ds, "Categories");
returnds.Tables["Categories"];
}
}
}
}
}
2、创建服务器端程序,新建一个解决方案,命名为Sever,添加引用上面编译好的DLL
代码如下:
usingSystem;
usingSystem.Windows.Forms;
usingSystem.Runtime.Remoting;//这个要添加引用
usingSystem.Runtime.Remoting.Channels;
usingSystem.Runtime.Remoting.Channels.Tcp;
//也可以改用HTTP传输实现
namespaceSever
{
publicpartialclassForm1 : Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidForm1_Load(objectsender, EventArgse)
{
//注意第二个参数要和客户端的一致,可以为TRUE也可以为FALSE
ChannelServices.RegisterChannel(newTcpServerChannel(9999), true);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteObject.RemoteTest), "heyu", WellKnownObjectMode.Singleton);
}
}
}
3、创建服务器端程序,新建一个解决方案,命名为Client,添加引用上面编译好的DLL
代码如下:
usingSystem;
usingSystem.Windows.Forms;
usingSystem.Runtime;
usingSystem.Runtime.Remoting; //这个要添加引用
usingSystem.Runtime.Remoting.Channels;
usingSystem.Runtime.Remoting.Channels.Tcp;
namespaceClient
{
publicpartialclassForm1 : Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidForm1_Load(objectsender, EventArgse)
{
ChannelServices.RegisterChannel(newTcpClientChannel(),true);
RemoteObject.RemoteTestobj = (RemoteObject.RemoteTest)Activator.GetObject(typeof(RemoteObject.RemoteTest), "tcp://192.168.1.103:9999/heyu");
this.dataGridView1.DataSource = obj.datable();
}
}
}
以上的程序可以说是不能够再简单的了,只适合于初学者!因为创建这样的程序存在很多的缺点:
1、没有使用配置文件,使得更改服务器时要重新编译程序。
2、创建出来的远程对象服务器端和客户端的是一样,为了代码的安全性,且降低客户端对远程对象元数据的相关性,我们有必要对这种方式进行改动。即在服务器端实现远程对象,而在客户端则删除这些实现的元数据。更好的解决办法是配合反射来处理。注册远程对象时,我们不要注册类,通过定义接口,而实现过程的类又继承这一个接口,通过类名去反射创建这一个类对象(注意是object不是class),然后通过强制类型转换,把这个object赋给接口,这样就可以完全的分离了!做成代理工厂。