.Net Remoting Code Example
Bookmark
 

Rating: 5.00/5
1 2 3 4 5
1 people have rated this article

 
Posted On: Jun 18 2008
Views: 907
BookMarked: 1
Downloads: 39
 
 
In this article, we'll take the basic .NET Remoting concepts and show you how to implement them in some simple remotable applications. 

Marshall Class

Marshaling by value
The remote object is serialized, passed to the client, and then reinstantiated;

Marshaling by reference
An object is controlled remotely by passing messages between the client and the remote object via proxy objects.

You can decide the nature of the object or which one of the above methods you want. Marshaling by reference can be achieved by inheriting the object from the System.MarshalByRefObject class. If it doesn't inherit from the MarshalByRefObject class, then object is Marshaling by value.

Looking more closely,
  • A serializable version of the remote object is created on the server.It is represented by System.Runtime.Remoting.ObjRef class. An ObjRef object stores all the relevant information needed to create remote object proxies (URL and type information) on the client side.

  • The serializable version is passed through the remoting channel(TCP or HTTP) to the client.

  • The serializable version of the object is deserialized at the client and parsed to create a copy of the remote object, placed inside a real proxy which handles communication to the server.

The RemotingServices Class

System.Runtime.Remoting.RemotingServices class is used for performing marshall() and unmarshall().It also contains Connect() whis is used by a client to connect to a remote object proxy and Disconnect() method, which is used by a client to disconnect from a remote object proxy.

Channels Class

.NET remoting provide two kinds of predefined channels:

1.TCP Channel
2.HTTP Channel

Thease channels are used to exchange information between remote applications.

All Channel object implements System.Runtime.Remoting.Channels.IChannel interface.

Sender will use the IChannelSender interface and receiver should use the IChannelReceiver interface. When you are creating your own custom channels, you must implement these interfaces on your class. This allows you to register your class as a channel type in remoting configuration. The default formatter for HttpChannel is SoapFormatter, and the default formatter for TcpChannel is BinaryFormatter.

TCP Channel

The System.Runtime.Remoting.Channels.Tcp namespace contains channels that use TCP/IP to exchange messages. By default it uses binary format for exchanging the messages, also you can specify your desired encoding format. It implements basic TCP sender receiver channel.

It uses three interfaces: IChannel, IChannelSender and IChannelReceiver.

Here are few examples of how to create a TcpChannel.

TcpChannel tc=new TcpChannel();

There are number of methods to declare a tcp channel. This constructor has no arguments. Also you can create a TCP constrauctor by passing the port number.

TcpChannel tc=new TcpChannel(55555);

The no-argument constructor creates a new TcpChannel instance, activating a client channel. In the second overload, we pass the constructor a port number (55555) where a server channel will be activated. These port is arbitary.

For a full list of port assignments, see http://www.iana.org/assignments/port-numbers.

Also there is another overload which takes three arguments.

System.Collections.Hashtable properyTable = new System.Collections.Hashtable();
properyTable["name"]="RedTcpChannel";
properyTable["port"] = "55555";
TcpChannel tc = new TcpChannel(properyTable, null,null);

Create a hashtable with name and port as propert names. We passed null to the client sink provider and server sink provider.This allows channel to select their own formatter for serialization.

Http channel

Http channel performs equivalent to TCP. By default Http Channel encodes messages in SOAP format. Although as with TCP, encoding is configurable.
A basic implementation of an HTTP channel is provided by the HttpChannel class. HttpChannel is a combination of HttpServerChannel and HttpClientChannel classes, and it implements IChannel, IChannelSender, and IChannelReceiver.

Here's an example of how to create an HttpChannel:

HttpChannel hc = new HttpChannel();
HttpChannel hc = new HttpChannel(66666);

The first activates a new client channel, whereas the second activates a server channel on port 66666.

Register a Channel

The ChannelServices class contains methods to control channel registration, resolution, and URL discovery .
Here's an example of how to register a Channel:

ChannelServices.RegisterChannel(tcpChannel);

It overloads with one parameter either TcpChannel or HttpChannel we created earlier.

Code Example

In this example, the server will marshal a simple order system in response to a client request, incrementing the value of the oreder value by one with each client request. We are going to create two console applications: OrderSystemClient and OrderSystemServer and one shared class library called OrderSystem. Creating the Shared Class Library The shared library will contain just one class which sends client about the next order id with a message. This class can be instantiated and the function NextOrder() called directly by a client in the same application. Note: To allow the object to be run outside the client application, we need our OrderSystem class to inherit from MarshalByRefObject.

Please follow the following steps to create Remote Object:

Step 1
Go to Visual Studio File>>Project>> In the New Project Window, Select Window in the Project Types Column, then Select Class Library in the Templates, Name the application as OrderSystem.

Step 2
Open Class1.cs file. Add the following to your Class1.cs.

namespace OrderSystem
{
public class Order: System.MarshalByRefObject
{
private int iNextOrderId;
public Order()
{
Console.WriteLine("Processing Order Started");
iNextOrderId = 100;
}
public int NextOrder()
{
iNextOrderId = iNextOrderId + 1;
Console.WriteLine("Next Order Will Be " + iNextOrderId); return iNextOrderId;
}
}
}

Step 3
Go to Visual Studio File>>Add>>New Project>>
In the New Project Window, Select Window in the Project Types Column, then Select Console Application in the Templates, Name the application as OrderSystemClient.

Step 4
Create proxy to remote object with url.It returns a proxy object that supports the same public as original and looks to our client very much like a real object running on the server. Eventhough Shared libray is not running on the client side,we need a reference for that.Right Click on OrderSystemClient Console Application Solution Explorer, then hit Add Reference. In Browse Tab,browse to the OrderSystem Shared library Bin and point to OrderSytem.dll so that it can have access to the description of OrderSytem's methods,the class metadata.

Step 5
Open Program.cs file. Add the following to your Program.cs.

 try
{
string url = "tcp://localhost:55555/Order";
Order order = (Order)RemotingServices.Connect(typeof(Order), url);
int iOrderId = order.NextOrder();
Console.WriteLine("Next Order For This Client Will Be " + iOrderId);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}

In the above code snippet, we create a URL, used to specify the location of the remote object.

The general URL format looks like this: Protocol://Server:UnusedPort/URITragetResource

In our example, the location of our server object is tcp://localhost:55555/OrderSystem. Having connected to the remote object,we can call the methods present in the remote object.

Step 6
Go to Visual Studio File>>Add>>New Project>>
In the New Project Window, Select Window in the Project Types Column, then Select Console Application in the Templates, Name the application as OrderSystemServer. Repeat Step 4.

Step 7
Right Click on OrderSystemClient Console Application Solution Explorer, then hit Add Reference. Then add System.Runtime.Remoting.dll assembly to the OrderSystemServer.

Step 8
Open Program.cs file in OrderSytemServer Console Application. Add the following to your Program.cs.

Console.WriteLine("Order System Server started");
TcpChannel channel = new TcpChannel(55555);
ChannelServices.RegisterChannel(channel);
Order order = new Order();
RemotingServices.Marshal(order, "Order");
Console.ReadLine();

Step 9
Note: Run the exe from DOS Command Prompt.

Start the server process OrderSytemServer.exe as shown in picture. Then Start the client process OrderSytemClient.exe as shown in picture and hit enter.



You can run multi-client(OrderSytemClient.exe) at the same time. If you run the client for multiple times,you can see diffrent order numbers in the console window.

Conclusion

I hope this article make you to familiar with many of the .Net remoting classes and methods you'll use to create remotable applications. In the next sequel,we will discuss about deploying the remote object in windows service.

Reference

Pro .NET 1.1 Remoting, Reflection, and Threading by Tobin Titus.


Rate This Article

Please Sign In In to post messages.