Thursday, 27 January 2011

Example code For .Net Remoting

create class library name as Sample Object using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace CodeGuru.Remoting
public class SampleObject : MarshalByRefObject
{
public SampleObject() // Constructor
{
}public string HelloWorld() // return string{return "Hello World!";}}} Create a Server To Expose the Remotable Object Create a new C# console application project. Add a class called SampleServer
namespace CodeGuru.Remoting
{
public class SampleServer
{
public static int Main(string [] args)
{
TcpChannel channel = new TcpChannel(8080);// Create an instance of a channel
ChannelServices.RegisterChannel(channel);

//Register as an available service with the name HelloWorld
RemotingConfiguration.RegisterWellKnownServiceType
(typeof(SampleObject), "HelloWorld", WellKnownObjectMode.SingleCall);
System.Console.WriteLine("Press the enter key to exit...");
System.Console.ReadLine();
return 0;
}
}}

Create a Client To Use the Remotable Object


public class SampleClient
{
public static int Main(string [] args)
{
// Create a channel for communicating w/ the remote object
// Notice no port is specified on the clientTcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
// Create an instance of the remote object
SampleObject obj = (SampleObject) Activator.GetObject
(typeof(CodeGuru.Remoting.SampleObject),"tcp://localhost:8080/HelloWorld" );
// Use the object
if( obj.Equals(null) )
{
System.Console.WriteLine("Error: unable to locate server");
}
else
{
Console.WriteLine(obj.HelloWorld());
}
return 0;
}
Create a new C# console application project. Add a class called SampleClient

No comments:

Post a Comment