C# Remoting 簡單實現


今天對C# Remoting進行了初步的學習,廢話不說...



RemotingModel: Talker.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace RemotingModel
{
    /// <summary>
    ///
    /// </summary>
   public class Talker: MarshalByRefObject
    {
       /// <summary>
       /// 說話
       /// </summary>
       /// <param name="word"></param>
       public void Talk(string word)
       {
           System.Console.WriteLine(word);
       }
    }
}
服務器端:是一個控制台,首先要添加對System.Runtime.Remoting的引用,然后添加對RemotingModel的引用
using System;
using System.Collections.Generic;
using System.Text;
 
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
 
using RemotingModel;
 
namespace RemotingServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //注冊通道
            TcpServerChannel channel = new TcpServerChannel("TalkChannel", 8090);  //端口隨便取
            ChannelServices.RegisterChannel(channel, true);
 
           //注冊遠程對象
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(Talker),
                "Talker",  
               WellKnownObjectMode.SingleCall);
           Console.ReadLine();
        }
    }
}
客服端:窗體:兩個textBox,一個button,設置textBox為多行。上面的textBox為:txtContent,下面的為:txtWord
 

添加引用(添加方法同上)
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemotingModel;
namespace RemotingClient
{
    public partial class Form1 : Form
    {
        private Talker _talk = null;
        public Form1()
        {
            InitializeComponent();
        }
       private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //操作遠程對象
                _talk.Talk(txtWord.Text.Trim());
                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);
            }
        }
    }
}
好了,下面看看結果:
 



注:以上所有操作均在同一台電腦,並且在同一個解決方案執行。
接下來會跟大家分享Remoting在局域網里的使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM