【C#】.NET Remoting ~ プロセス間通信 ~

■ はじめに

 * JavaRMI (Remote Method Invocation) のようなことを C# で行う
 * .NET Framework 3.0から導入されたWCF(以下の関連記事を参照)でも同じことができるし、
   そっちの方がいいと思うが、.NET Remoting というやり方を学ぶ
WCF ~ 基礎知識編 ~
https://blogs.yahoo.co.jp/dk521123/22254537.html

■ サンプル

 * オブジェクト、サーバーおよびクライアントの 3 つの部分で構成する。
 * この三つを別々のプロジェクトで作成する

オブジェクト

 * クラスとして作成し、実行しておく
 * ポイントは「MarshalByRefObject」を継承していること!!
プロジェクト「RmiForMethod」
using System;

namespace RmiForMethod
{
    public class Class1 : MarshalByRefObject
    {
        public Class1()
        {
            Console.WriteLine("Start!!");
        }

        public void SayHellowWorld()
        {
            Console.WriteLine("Hello World");
        }
    }
}

サーバー側

 * System.Runtime.Remotion を参照追加しておく
 * RmiForMethodも参照追加しておく
 * コンソールアプリケーションとして作成し、実行しておく
プロジェクト「RmiForServer」
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

namespace RmiForServer
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpChannel ch = new HttpChannel(4000);
            ChannelServices.RegisterChannel(ch, false);
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(RmiForMethod.Class1),
                "MyServer", WellKnownObjectMode.Singleton);

            Console.WriteLine("Server is started.");
            Console.WriteLine("Press <Enter> Key to exit.");
            Console.ReadLine(); // to stop
        }
    }
}

クライアント

 * RmiForServer、RmiForMethodを参照追加しておく
 * Windowsアプリケーション(Windows Form。ボタンを追加)として作成し、実行しておく
 * ボタン押下後、「サーバー側」のコンソールアプリケーションに「Hello World」などが表示されるはず
プロジェクト「RmiForClient」
using System;
using System.Windows.Forms;

namespace RmiForClient
{
    public partial class Form1 : Form
    {
        RmiForMethod.Class1 obj;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.obj.SayHellowWorld();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Runtime.Remoting.
                RemotingConfiguration.RegisterWellKnownClientType(
                typeof(RmiForMethod.Class1),
                "http://localhost:4000/MyServer");
            this.obj = new RmiForMethod.Class1();
        }
    }
}

関連記事

WCF ~ 基礎知識編 ~

https://blogs.yahoo.co.jp/dk521123/22254537.html