遠程開發分布式C#編程執行個體

來源:互聯網
上載者:User

從用戶端到服務端的遠程網路通訊,發送訊息並返回遠程訊息。
遠程對象(RemoteTest)C# 類庫代碼部分:

using System;

namespace RemoteTest
{
   public class TestLoader : MarshalByRefObject
   {
        public TestLoader()
        {
            string stringWrite = "stor load.";
           Console.WriteLine(stringWrite);
        }
       public string sayHello(string msg)
       {
           Console.WriteLine("Message: { 0 } ", msg);
           Console.WriteLine("Welcome to Message send Systems");

           string stc = "Hello from remote";
           return stc;
        }
    }
}

RemoteTest組件中的 TestLoader 類繼承了 System.MarshalByRefObject 類,便讓用戶端能訪問該遠程對象了。

服務端(Server)命令列應用程式代碼部分:

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

namespace Server
{
   public class Program
   {
       public static void Main(string[] args)
       {
           TcpServerChannel channel = new TcpServerChannel(9932);
           ChannelServ ices.RegisterChannel(channel, false);
           RemotingConfiguration.RegisterWellKnownServiceType(typeof(TestLoader),"TestLoader",WellKnownObjectMode.SingleCall);
           Console.WriteLine("Hello From Server");
           Console.ReadLine();
        }
    }
}

註:引用添加組件:System.Runtime.Remoting(下同)。

用戶端(Client)命令列應用程式代碼部分:

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

namespace Client
{
   public class ClassClient
   {
       public static void Main(string[] args)
       {
           string stringTcp = "tcp://localhost:9932/TestLoader";
           TestLoader loader = (TestLoader)Activator.GetObject(typeof(RemoteTest.TestLoader),stringTcp);
           string msg;
           Console.Write("Enter Message: ");
           msg = Console.ReadLine();
           Console.WriteLine("Message: {0}" + msg);
           string res = loader.sayHello(msg);
           Console.WriteLine(res);
        }
    }
}

這裡對new 管道聲明的那兩行已略寫。

 

程式調試:啟動Server後,再啟動Client。輸入值後關閉Client,值便在Server中顯示。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.