Wednesday, November 14, 2007

.NET Remoting (2) SimpleRemoting




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;

}

}

}



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)

{

//get the remote object through TCP channel

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

}

//get the remote object through HTTP channel

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

}

Console.WriteLine(

"Client1 TCP HelloMethod {0}",

obj1.HelloMethod("Caveman1"));

Console.WriteLine(

"Client2 HTTP HelloMethod {0}",

obj2.HelloMethod("Caveman2"));

Console.ReadLine();

}

}

}

In this code, select the server project, press Ctrl + F5 to start it. Then select the client project to start debugging, you will see the client can get the HelloServer's object and call its HelloMethod.

blog comments powered by Disqus