Remoting分布式开发在局域网中的应用

先弄清一下流程吧:

   1>定义远程对象(继承自MarshalByRefObject)
   2>创建一个Server端作为宿主(注册通道、注册远程对象)
   3>创建客户端(注册通道、通过URL获取Server端的远程对象的代理、通过代理操作远程对象)

服务器IP:10.10.1.35   端口号:8090

如果使用的端口号已经被占用会提示:

具体操作代码:

 1.创建一个操作具体的项目RemotingModel

 

namespace RemotingModel
{
    //记得把类的访问修饰符改为public
    public class Talker : MarshalByRefObject//继承自该MarshalByRefObject
    {
        public void Talk(string word)
        {
            Console.WriteLine(word);
        }
    }
}

 

 2.添加一个服务器端项目RemotingServer:这个项目在服务器端10.10.1.35机器上

   1>添加引用System.Runtime.Remoting和RemotingModel项目

   2>添加如下代码:

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

using RemotingModel;

 

static void Main(string[] args)
        {
            //注册通道(添加引用RemotingModel和System.Runtime.Remoting)
            TcpServerChannel channel = new TcpServerChannel("TalkChannel", 8090);
            ChannelServices.RegisterChannel(channel, false);

            //注册远程对象
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(Talker),
                "Ser_Talker",
                WellKnownObjectMode.SingleCall
                );

            Console.ReadLine();
        }

 

 3.添加一个客户端项目RemotingClient:这个项目在客户端机器上

    同样添加那两引用

  

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

using RemotingModel;

namespace RemotingClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Talker _talker = null;
        private void button1_Click(object sender, EventArgs e)
        {
            //操作远程对象
            _talker.Talk(txt_word.Text.Trim());

            //Do other things
            txt_content.Text = "发送成功:" + txt_word.Text.Trim();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //注册通道
            TcpClientChannel channel = new TcpClientChannel();
            ChannelServices.RegisterChannel(channel, false);

            //获取远程对象
            _talker = (Talker)Activator.GetObject(typeof(Talker), "TCP://10.10.1.35:80/Ser_Talker");//TCP://10.10.1.35:8090/Ser_Talker
        }
    }
}

 注意:如果客户端和服务器端ChannelServices.RegisterChannel(channel, true);这里是true的时候会报错:

如果端口号写的不一致就会出现如下错误:

当然如果客户端和服务器端都在本机上运行的时候这里的true也可以的。

生成之后你直接在服务器端和客户端下打开bin>Debug>文件夹下的.exe就可以实现效果了。

这样的话就ok了你在本机上发的消息马上就能在服务器10.10.1.35上看到消息了。

posted @ 2012-08-26 23:13  aspneteye  阅读(305)  评论(0编辑  收藏  举报