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();
}
}
}