Tuesday, May 8, 2007

Remoting in .NET

.NET Remoting provides a way for application in different machines/domains to communicate with each other. Remoting provides a powerful yet an easy way to communicate with object in different app domains. Any object which executes outside the app domain can be considered as Remote.

Remote objects are accessed via Channels, Channels can be thought of as Transport mechanism to pass messages to and from remote objects. All the method calls along with the parameters are passed to the remote object thru the channel viz. HTTP or TCP.

Step 1: Creating the Server Server.cs On Machine1

using System;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.HTTP;
namespace Server
{
public class ServiceClass : MarshalByRefObject
{
public void AddMessage (String msg)
{
Console.WriteLine (msg);
}
}
public class ServerClass
{
public static void Main ()
{
HTTPChannel c = new HTTPChannel (1095); ChannelServices.RegisterChannel (c);
RemotingServices.RegisterWellKnownType ("Server","Server.ServiceClass","ServiceClass",WellKnownObjectMode.Singleton);
Console.WriteLine ("Server ON at 1095");
Console.WriteLine ("Press enter to stop the server...");
Console.ReadLine ();
}
}
}

This will create a proxy called Server.dll which will be used to access the remote object

Client Code TheClient.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.HTTP;
using Server;
public class TheClient
{
public static void Main (string[] args)
{
HTTPChannel c = new HTTPChannel (1077); ChannelServices.RegisterChannel (c);
ServiceClass sc = (ServiceClass) Activator.GetObject (typeof
(ServiceClass),http://:1095/ServiceClass);
sc.AddMessage ("Hello From Client");
}
}

No comments: