Wednesday, November 12, 2008

Remoting with .NET

Remoting simplies development of client-server or service-oriented applications greatly. To start off, you need an interface that declares all the methods that you would like to make available to the client application. This interface should ideally be placed in a client library that you can reference from both the server and the client application, but you can also define the interface in both applications.

Example: Interface (Server & Client)


namespace Sinkhole1
{
public interface IWiseMonk
{
int getSquare(int a);
}
}


We now need to define the class implements this interface.

Example. Service class (Server)


namespace Sinkhole1
{
[Serializable]
public class WiseMonk : MarshalByRefObject, IWiseMonk
{
public int getSquare(int a)
{
return a * a;
}
}
}


Next, we need to make a hosting application that can serve the requests of the client application. The end point for the service class needs to be defined. The server application should ideally be a Windows Service application, but can also be a console or windows forms application.

Example. Server application (Server)


namespace Sinkhole1
{
class Program
{
static void Main(string[] args)
{
RemotingConfiguration.ApplicationName = "WiseMonk";
WellKnownServiceTypeEntry wkste = new WellKnownServiceTypeEntry(typeof(WiseMonk), "MathEngine", WellKnownObjectMode.SingleCall);
RemotingConfiguration.RegisterWellKnownServiceType(wkste);

TcpChannel tch = new TcpChannel(109);
ChannelServices.RegisterChannel(tch, false);

//Keep the server waiting for client requests
Console.ReadLine();
}
}
}


The client application doesn't really have all that much to do - it needs to get an instance of the service object and make method calls.

Example. Client application (Client)


namespace SinkHole1Client
{
class Program
{
static void Main(string[] args)
{
IWiseMonk iwm = (IWiseMonk) Activator.GetObject(typeof(IWiseMonk), "tcp://localhost:109/WiseMonk/MathEngine");

Console.Write(iwm.getSquare(5));

Console.ReadLine();
}
}
}

No comments: