Friday, November 16, 2007

.NET Remoting (5) Value vs RefObject

using System;

using System.Collections.Generic;

using System.Text;

namespace RemotingSamples

{

public class HelloServer : MarshalByRefObject

{

public HelloServer()

{

Console.WriteLine("HelloServer activated");

}

public String HelloMethod(String name)

{

Console.WriteLine(

"Server Hello.HelloMethod : {0}", name);

return "Hi there " + name;

}

public MySerialized GetMySerialized()

{

return new MySerialized(4711);

}

public MyRemote GetMyRemote()

{

return new MyRemote(4712);

}

}

}

using System;

using System.Collections.Generic;

using System.Text;

namespace RemotingSamples

{

[Serializable]

public class MySerialized

{

public MySerialized(int val)

{

a = val;

}

public void Foo()

{

Console.WriteLine("MySerialized.Foo called");

}

public int A

{

get

{

Console.WriteLine("MySerialized.A called");

return a;

}

set

{

a = value;

}

}

protected int a;

}

public class MyRemote : System.MarshalByRefObject

{

public MyRemote(int val)

{

a = val;

}

~MyRemote()

{

Console.WriteLine("MyRemote destructor");

}

public void Foo()

{

Console.WriteLine("MyRemote.Foo called");

}

public int A

{

get

{

Console.WriteLine("MyRemote.A called");

return a;

}

set

{

a = value;

}

}

protected int a;

}

}


using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels.Http;

namespace RemotingSamples

{

public class Server

{

public static int Main(string [] args)

{

TcpChannel chan1 = new TcpChannel(8085);

HttpChannel chan2 = new HttpChannel(8086);

ChannelServices.RegisterChannel(chan1);

ChannelServices.RegisterChannel(chan2);

RemotingConfiguration.RegisterWellKnownServiceType

(

typeof(HelloServer),

"SayHello",

WellKnownObjectMode.SingleCall

);

System.Console.WriteLine("Press Enter key to exit");

System.Console.ReadLine();

return 0;

}

}

}



using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels.Http;

using System.IO;

namespace RemotingSamples

{

public class Client

{

public static void Main(string[] args)

{

TcpChannel chan1 = new TcpChannel();

ChannelServices.RegisterChannel(chan1);

HelloServer obj1 = (HelloServer)Activator.GetObject(

typeof(RemotingSamples.HelloServer),

"tcp://localhost:8085/SayHello");

if (obj1 == null)

{

System.Console.WriteLine(

"Could not locate TCP server");

}

MySerialized ser = obj1.GetMySerialized();

if (!RemotingServices.IsTransparentProxy(ser))

{

Console.WriteLine("ser is not a transparent proxy");

}

ser.Foo();

MyRemote rem = obj1.GetMyRemote();

if (RemotingServices.IsTransparentProxy(rem))

{

Console.WriteLine("rem is a transparent proxy");

}

rem.Foo();

System.Console.ReadLine();

}

}

}

blog comments powered by Disqus