Thursday, November 15, 2007

.NET Remoting (4) Singleton vs SingleCall

using System;

using System.Collections.Generic;

using System.Text;

namespace RemotingSamples

{

public class HelloServer : MarshalByRefObject

{

public int callCounter = 0;

public HelloServer()

{

Console.WriteLine("HelloServer activated");

}

public String HelloMethod(String name,

out int counter)

{

counter = ++callCounter;

Console.WriteLine(

"Server Hello.HelloMethod : {0} Counter :{1}",

name, callCounter);

return "Hi there " + name;

}

}

}



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.Singleton

);

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");

}

HttpChannel chan2 = new HttpChannel();

ChannelServices.RegisterChannel(chan2);

HelloServer obj2 = (HelloServer)Activator.GetObject(

typeof(RemotingSamples.HelloServer),

"http://localhost:8086/SayHello");

if (obj2 == null)

{

System.Console.WriteLine(

"Could not locate HTTP server");

}

int counter;

Console.WriteLine(

"Client1 TCP HelloMethod {0} Counter {1}",

obj1.HelloMethod("Caveman1", out counter),

counter);

Console.WriteLine(

"Client2 HTTP HelloMethod {0} Counter {1}",

obj2.HelloMethod("Caveman2", out counter),

counter);

Console.WriteLine(

"Client2 HTTP HelloMethod {0} Counter {1}",

obj2.HelloMethod("Caveman3", out counter),

counter);

Console.ReadLine();

}

}

}

In this code, if WellKnownObjectMode.Singleton then the result will be shown as:

Client1 TCP HelloMethod Caveman1 Counter 1

Client2 HTTP HelloMethod Caveman2 Counter 2

Client2 HTTP HelloMethod Caveman3 Counter 3

if WellKnownObjectMode.SingleCall then the result will be shown as:
Client1 TCP HelloMethod Caveman1 Counter 1
Client2 HTTP HelloMethod Caveman2 Counter 1
Client2 HTTP HelloMethod Caveman3 Counter 1

blog comments powered by Disqus