リモート処理
プログラミングC# p493
まずはインタフェースを作る。
public interface IRemote { string Hello(); double Add(double a, double b); }
csc /t:library IRemote.cs
次にサーバを作る。
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; namespace HelloAddServerNS { class HelloAddServer : MarshalByRefObject, IRemote { public string Hello() { return "Hello, World!"; } public double Add(double a, double b) { return a + b; } } class ServerTest { static void Main(string[] args) { HttpChannel chan = new HttpChannel(65100); ChannelServices.RegisterChannel(chan, false); RemotingConfiguration.RegisterWellKnownServiceType ( typeof(HelloAddServerNS.HelloAddServer) , "theEndPoint" , WellKnownObjectMode.Singleton ); Console.ReadLine(); } } }
Mainの中はオマジナイ多し。とりあえず動かすのが目的なので無視。
コンパイルはこう。
csc /R:IRemote.dll HelloAddServer.cs
で、HelloAddServerを起動して、待ちうけしておく。
最後にクライアントを作る。
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; class HelloAddClient { static void Main(string[] args) { HttpChannel chan = new HttpChannel(0); ChannelServices.RegisterChannel(chan, false); Object obj = RemotingServices.Connect ( typeof(IRemote) , "http://localhost:65100/theEndPoint" ); IRemote remote = obj as IRemote; Console.WriteLine(remote.Hello()); Console.WriteLine(remote.Add(12, 23)); } }
コンパイルはこう。
csc /R:IRemote.dll HelloAddClient.cs
で、HelloAddClientを実行してみると、結果はこうなる。
Hello, World! 35
まあ普通に動いた。これだけでリモート処理を実装できるのであれば、.NET内に閉じる場合に限り、Webサービスは必要ないですね。まあTPOに応じて使い分けなんでしょうけど。
ところで、HelloAddClient.csの
HttpChannel chan = new HttpChannel(0); ChannelServices.RegisterChannel(chan, false);
の2行は無駄っぽいなあと思って、コメントアウトしてみましたが、普通に動きました。うーん。なんのオマジナイだったんだろう。。と思って良く読んでみたら、
CLRはTCPおよびHTTPチャネルを標準のチャネルとして登録していますが、コールバックの受信や非標準チャネルの登録を行う場合は、クライアント上でチャネルを登録する必要があります。
とのこと。
このサンプルの場合、コールバックは受信しないし、HTTPチャネルは標準だしで、不要だったのでしょう。きっと。