Remoting简单使用

1、RemotingModel

public class Talker: MarshalByRefObject
    {
        /// <summary>
        /// 说话
        /// </summary>
        /// <param name="word"></param>
        public void Talk(string word)
        {
            System.Console.WriteLine(word);
        }
    }

  必须继承MarshalByRefObject

2、RemotingServer

使用控制台程序

        static void Main(string[] args)
        {
            //注册通道
            TcpServerChannel channel = new TcpServerChannel("TalkChannel", 8090);
            ChannelServices.RegisterChannel(channel, true);
            //注册远程对象
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(Talker), "Talker", WellKnownObjectMode.SingleCall);
            Console.ReadLine();
        }

3、RemotingClient

使用窗体程序

 代码如下:

        private Talker _talk = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //操作远程对象
                _talk.Talk(txtWord.Text.Trim());
                txtContent.Text = "";
                txtContent.Text = "发送成功" + txtWord.Text.Trim();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //注册通道
                TcpClientChannel channel = new TcpClientChannel();
                ChannelServices.RegisterChannel(channel,true);
                //获取远程对象
                _talk = (Talker)Activator.GetObject(typeof(Talker), "TCP://localhost:8090/Talker");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

  4、演示效果

 原版:https://blog.csdn.net/u011555996/article/details/52933116

2020-12-14 10:19:55 记录

原文地址:https://www.cnblogs.com/sailing92/p/14131819.html