[C#] クラスの動的生成あれこれ(その2)

今回は少し長くなるが、空間を越えた(ネットワーク越しの)オブジェクトを構築するサンプル。
下準備がえらく長くなるけど、めげないでね。

簡単に手順を説明
●サーバ側

  1. サーバプロジェクト作成
  2. サーバソースをメインソースとする
  3. 生成クラスソースを追加
  4. ビルド
  5. 実行
  6. コンソールが起動し、待ち状態になる

●クライアント側

  1. クライアント作成
  2. クライアントソースをメインソースとする(足りないところは追加してね)
  3. 生成クラスソースを追加
  4. ビルド
  5. 実行
  6. コンソールが起動し、上手くいけばサーバ側コンソールに何か出力され終了する

ちなみにこのサンプル作るのに、4時間ぐらいかかりました。
なんかWeb漁ってもあんまり出てなくて、苦労しましたよ・・(^^;

  • サーバーソース


using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace RemotingSamples
{
public class Sample
{
public static int Main(string [] args)
{
TcpChannel chan = new TcpChannel(8085);
ChannelServices.RegisterChannel(chan);

RemotingConfiguration.ApplicationName = "HelloService";
RemotingConfiguration.RegisterActivatedServiceType(typeof(HelloServer));

System.Console.WriteLine("Hit <enter> to exit...");
System.Console.ReadLine();
return 0;
}
}
}

  • クライアントソース Activator.CreateInstance (Type, Object, Object) のサンプル


object[] activationAttributes
= {new System.Runtime.Remoting.Activation.UrlAttribute("tcp://localhost:8085")};
// "tcp://localhost:8085/HelloService" でもOK

RemotingSamples.HelloServer hs =
System.Activator.CreateInstance( typeof(RemotingSamples.HelloServer), null, activationAttributes)
as RemotingSamples.HelloServer;

hs.HelloMethod("hoge");

  • 構築するクラス


using System;

namespace RemotingSamples
{
public class HelloServer : MarshalByRefObject
{

public HelloServer()
{
Console.WriteLine("HelloServer activated");
}

public String HelloMethod(String name)
{
Console.WriteLine("Hello.HelloMethod : {0}", name);
return "Hi there " + name;
}
}
}