C#远程数据访问(Remoting)

作者在 2009-01-02 16:53:13 发布以下内容

1、  创建一个远程对象(DLL):新建一个解决方案(类库),命名为RemoteObject

创建一个类 RemoteTest,代码如下

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

namespace RemoteObject

{

    public class RemoteTest : System.MarshalByRefObject//这是不能少的

    {

        SqlConnection con;

        DataSet ds;

        SqlDataAdapter da;

        string conStr = "data source=HEYU\\SQLEXPRESS;initial catalog=schooldatabase;integrated security=SSPI;persist security info=False;packet size=4096";

        string queryStr = "select   *   from   book";

        public DataTable datable()

        {

            using (con = new SqlConnection(conStr))

            {

                using (da = new SqlDataAdapter(queryStr, con))

                {

                    ds = new DataSet();

                    da.Fill(ds, "Categories");

 

                    return ds.Tables["Categories"];

                }

            }

        }

    }

}

 

2、创建服务器端程序,新建一个解决方案,命名为Sever,添加引用上面编译好的DLL

代码如下:

using System;

using System.Windows.Forms;

using System.Runtime.Remoting;//这个要添加引用

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

//也可以改用HTTP传输实现

namespace Sever

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

//注意第二个参数要和客户端的一致,可以为TRUE也可以为FALSE

            ChannelServices.RegisterChannel(new TcpServerChannel(9999), true);

RemotingConfiguration.RegisterWellKnownServiceType(

typeof(RemoteObject.RemoteTest), "heyu", WellKnownObjectMode.Singleton);

        }

    }

}

 

3创建服务器端程序,新建一个解决方案,命名为Client,添加引用上面编译好的DLL

代码如下:

using System;

using System.Windows.Forms;

using System.Runtime;

using System.Runtime.Remoting; //这个要添加引用

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

 

namespace Client

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            ChannelServices.RegisterChannel(new TcpClientChannel(),true);

            RemoteObject.RemoteTest obj = (RemoteObject.RemoteTest)Activator.GetObject(typeof(RemoteObject.RemoteTest), "tcp://192.168.1.103:9999/heyu");

            this.dataGridView1.DataSource = obj.datable();

        }

    }

}

 

以上的程序可以说是不能够再简单的了,只适合于初学者!因为创建这样的程序存在很多的缺点:

1、没有使用配置文件,使得更改服务器时要重新编译程序。

2、创建出来的远程对象服务器端和客户端的是一样,为了代码的安全性,且降低客户端对远程对象元数据的相关性,我们有必要对这种方式进行改动。即在服务器端实现远程对象,而在客户端则删除这些实现的元数据。更好的解决办法是配合反射来处理。注册远程对象时,我们不要注册类,通过定义接口,而实现过程的类又继承这一个接口,通过类名去反射创建这一个类对象(注意是object不是class,然后通过强制类型转换,把这个object赋给接口,这样就可以完全的分离了!做成代理工厂。

3、待续。。。。。。

默认分类 | 阅读 11067 次
文章评论,共0条
游客请输入验证码
浏览31903次
文章归档
最新评论