以前のエントリ で書いたけど、
米林 さんが紹介していた Merapi が .NET Remoting みたいなのかなと思ったので .NET Remoting を触ってみる。
サーバー側は、IpcServerChannelのサンプルコードを実行する。
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; public class IpcServer { public static void Main () { // Create and register an IPC channel IpcServerChannel serverChannel = new IpcServerChannel("remote"); ChannelServices.RegisterChannel(serverChannel); // Expose an object RemotingConfiguration.RegisterWellKnownServiceType( typeof(Counter), "counter", WellKnownObjectMode.Singleton ); // Wait for calls Console.WriteLine("Listening on {0}", serverChannel.GetChannelUri()); Console.ReadLine(); } } public class Counter : MarshalByRefObject { private int count = 0; public int Count { get { return(count++); } } }
これを実行してから、次のクライアント側IpcClientChannelのサンプルコードを実行する。
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; public class Client { public static void Main () { IpcClientChannel clientChannel = new IpcClientChannel(); ChannelServices.RegisterChannel(clientChannel); RemotingConfiguration.RegisterWellKnownClientType( typeof(Counter) , "ipc://remote/counter" ); Counter counter = new Counter(); Console.WriteLine("This is call number {0}.", counter.Count); } } public class Counter : MarshalByRefObject { private int count = 0; public int Count { get { return(count++); } } }
Client 側のコードを実行する度に、表示される数字が 1 づつ増えていく。
Client 側で
Counter counter = new Counter();
としているが、ここではサーバー側のインスタンスが返されている。(と思われる。.NET Remoting の仕組みはちゃんと勉強してないので間違ってたらゴメンナサイ…)
※訂正
思いっきり嘘書いてました。サーバー側のインスタンスが返される訳ないです。new Counter としていますが、
実際には Proxy が返されて Proxy 経由で サーバーに処理が投げられてます。
んで、サーバー側 のコードで
RemotingConfiguration.RegisterWellKnownServiceType( typeof(Counter), "counter", WellKnownObjectMode.Singleton );
の 第三引数の WellKnownObjectMode を Singleton にしているため、何回呼び出しても同じインスタンスが返ってくる。
だから、Client 側のコードを実行する度に、数字が増えていく。
これを、
RemotingConfiguration.RegisterWellKnownServiceType( typeof(Counter), "counter", WellKnownObjectMode.SingleCall );
に変更すると、Client 側を何回実行しても、表示される 数字は、0 になる。