Click here to Skip to main content
15,881,651 members
Articles / Programming Languages / C#
Article

Simple Sample for .NET Remoting

Rate me:
Please Sign up or sign in to vote.
4.19/5 (10 votes)
14 Feb 2007CPOL3 min read 62.2K   3.5K   38   7
This article is for beginners
Remoting

Introduction

The intention of writing this article is to make beginners understand the concept of .NET Remoting. The sample project along with this article is a simple application which clearly gives an idea for a beginner in .NET Remoting.

.NET Remoting

.NET Remoting provides a framework for designing distributed applications. Remoting is an architecture which enables communication between objects living in different application domains. Application domain is a small execution unit of an application. An application domain cannot access the code of another application domain. Communication among the objects across the application boundaries takes place through a process called as Marshalling.

Marshalling

Marshalling is a mechanism of passing objects across the application boundaries by serialization and deserialization.

Communication between two objects takes place through a channel.

Channels

Channels are the objects that transport messages across application boundaries. The remote objects are accessed through channels which are transport protocols which enable communication between the client and a remote object which lies in different application boundaries.

Remoting

Implementation

Let me directly get into the implementation. The steps involved in implementing remoting are as follows. Create a class which will act as a remote object in the server. This class should be derived from MarshalByRefObject. Objects created from this class can be accessed from the client via the reference which is passed to the client. This reference is used by a proxy object which pretends as the remote object.

C#
using System;
using System.Diagnostics;

namespace Sample.RemoteObject
{
    /// <summary>
    /// Used as the remote component which will be accessed by the clients 
    /// </summary>
    public class RemoteCalculator:MarshalByRefObject
    {
        public RemoteCalculator()
        {
            //Check whether a source exists with the name given
            if (!EventLog.SourceExists("RemoteObject"))
            {
                //If not create a source
                EventLog.CreateEventSource("RemoteObject", "Application");
            }
        }
        public int Add(int a, int b)
        {
            //Log the information to keep track of the calls made from the 
            //client
            EventLog.WriteEntry("RemoteObject", 
                        String.Format("Addition of {0} and {1} ", a, b));
            return a + b;
        }

        public int Multiply(int a, int b)
        {
            //Log the information to keep track of the calls made from the 
            //client
            EventLog.WriteEntry("RemoteObject", 
                          String.Format("Addition of {0} and {1} ", a, b));
            return a * b;
        } 
    }
}

Create the Server application which listens to the request of clients in another project. And make a reference to the DLL which implements the Remote object (RemoteCalculator) in the application.

C#
//Registering the TCP channel
_serverChannel = new TcpChannel(_port);
ChannelServices.RegisterChannel(_serverChannel);
//Registering the server component as a server activated object (SOA)
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteCalculator),
                   "RemoteCalculator", WellKnownObjectMode.Singleton);
btnListen.Text = "Stop Listening";

Create a channel where the client requests will be received. The channel which is created has to be registered. Remote objects can be classified as:

  • Server activated objects (SAO)
  • Client activated objects (CAO)

Server Activated Objects

Server activated objects are remote objects where the lifetime of the objects is controlled by the server. Two possible activation modes of a SAO are SingleCall and Singleton.

SingleCall activation mode is used for the purpose of responding to just one client request.

Singleton is used where one instance of server remote object is accessed by many clients.

Client Activated Objects

Client activated objects are objects where the lifetime is directly controlled by the client.

After registering the channel, the remotable object has to be registered in the server using RemotingConfiguration.RegisterWellKnownServiceType method.

In the sample application, addition and multiplication calculation is done by the remote object residing in the server which is accessed from the client using remoting.

C#
/// <summary>
/// Addition and Multiplication is done at the server through remoting
/// </summary>
private string Calculate(Operation operation,int number1, int number2)
{
    int result ;
    //check whether channel is created
    if (_clientChannel == null)
    {  
        //Create the channel
        _clientChannel = new TcpChannel();
        //Register  the channel 
        ChannelServices.RegisterChannel(_clientChannel);
     }
     //Create a proxy object to access the remote calculator
     _remoteCalculator = 
           (RemoteCalculator)Activator.GetObject(typeof(RemoteCalculator), 
               "tcp://" + _server + ":" + _port + "/RemoteCalculator");
     if (operation.Equals(Operation.Addition))
     {
         result = _remoteCalculator.Add(number1, number2);
     }
     else
     {
         result = _remoteCalculator.Multiply(number1, number2);
     }
     return Convert.ToString(result);
}

On the client side, a channel has to be created to access the remote object. A proxy object is created in the client side using:

C#
remoteCalculator = (RemoteCalculator)Activator.GetObject(typeof(RemoteCalculator), 
    "tcp://" + _server + ":" + _port + "/RemoteCalculator"); 

Activator.GetObject method is used to create a proxy for SAO. In case of CAO, Activator.CreateInstance method is used. In the sample application, the server name and the port are picked from the configuration (App.Config) file so that the server name and port number can be changed easily.

C#
//Get the server name and server port from the configuration file
_server = ConfigurationManager.AppSettings["Server"];
_port = ConfigurationManager.AppSettings["ServerPort"];

Each call to remote object is tracked in the Event Viewer.You can check the logged information in the eventviewer by using the command eventvwr.msc in the command prompt (cmd.exe) or by exploring the path "Control Panel/Administrative Tools/Event Viewer".Check the logged information in the "Application" Log. You will find that each call to a remote object is logged.

I hope this simple sample application gives you an understanding of Remoting.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Nero theZero14-Mar-14 0:08
Nero theZero14-Mar-14 0:08 
QuestionError Pin
javed21628-Jan-13 2:43
javed21628-Jan-13 2:43 
QuestionHow to get the RemoteObject that arrives to the server? Pin
Deza_20-Feb-07 7:39
Deza_20-Feb-07 7:39 
QuestionWhy Vista .NET 3.0? Pin
GreenOrc13-Feb-07 3:27
GreenOrc13-Feb-07 3:27 
QuestionMissing image? Pin
Rudolf Jan5-Feb-07 8:32
Rudolf Jan5-Feb-07 8:32 
GeneralRemoting with Spring.NET Pin
mrxl5-Feb-07 2:01
mrxl5-Feb-07 2:01 
GeneralGood Job Pin
Ri Qen-Sin4-Feb-07 23:37
Ri Qen-Sin4-Feb-07 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.