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

Just .NET Remoting

Rate me:
Please Sign up or sign in to vote.
4.45/5 (22 votes)
28 Aug 2007CPOL3 min read 45.5K   657   52   9
The simplest .NET Remoting project possible.

Screenshot - JustRemoting.png

Introduction

This is a simple .NET Remoting example in three parts: the interface, the server, and the client. The client asks for your name, then sends it to the server. The server returns a personal greeting.

Background

I wanted to see the simplest .NET Remoting project possible. Although there are many resources that explain .NET Remoting, I found many examples were either incomplete, or got convoluted by configuration files, sinks, or activation modes. This example is by no means comprehensive, but it's a good place to start if you're new to .NET Remoting or C#.

Using the code

Download the code, and open the solution in Visual Studio 2005. Build the solution. The tricky part is starting both the client and the server application in the debugger. Select Project in the menu, and choose "Select Startup projects...". Then, select Multiple Startup Projects, and set the RemoteClient and RemoteServer actions to start. Click OK, and hit F5.

The interface

The RemoteInterface project contains just one source file, HelloInterface.cs. It simply identifies the methods that will be performed by the remote object. This file will be compiled into an assembly (a DLL) that contains the meta-data needed by both the client project and the server project to talk to one another.

C#
// HelloInterface.cs
using System;

namespace RemoteInterface
{
    public interface HelloInterface
    {
        String HelloMethod(String name);
    }
}

The server

The server waits for the clients to introduce themselves. When you open the solution, note that RemoveServer contains a project reference to RemoteInterface. This tells the compiler that anything defined in the RemoteInterface project (in our case, the HelloInterface class) is used by the HelloServer project.

JustRemoting solution showing project references

You should also notice two source files: HelloServer.cs and RemoteServerMain.cs. In the example below, HelloServer implements the HelloInterface we just defined, plus inherits from another class: MarshalByRefObject. If we want to use a class with .NET Remoting, we have to inherit from MarshalByRefObject.

C#
// HelloServer.cs
using System;
using RemoteInterface;

namespace RemoteServer
{
    // HelloServer inherits from MarshalByRef object, making 
    // it serializable, and therefore remotable
    // Hello server also implements the HelloInterface 
    public class HelloServer : MarshalByRefObject, HelloInterface
    {
        // Constructor - called when object is created; experiment 
        // with activation modes in RemoteServerMain.cs to see how 
        // it impacts the constructor call
        public HelloServer()
        {
            Console.WriteLine("HelloServer activated");
        }

        public String HelloMethod(String name)
        {
            Console.WriteLine("HelloServer.HelloMethod : {0}", name);
            return "Hi there " + name;
        }
    }
}

In the next file, the Main method sets up the .NET Remoting infrastructure. It opens a listening TCP/IP port, and associates our HelloServer class with a URI, SayHello. This is the neat part: you can have as many classes as you want, all on the same port, each using a different URI.

C#
// RemoteServerMain.cs
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace RemoteServer {
    public class RemoteServer {
        public static int Main(string [] args) {

            Console.Title = "RemoteServer";

            // Opens passive or "listening" socket, 
            // or throws an exception
            TcpChannel chan = new TcpChannel(8084); 
            
            // Lets the remoting system use the socket
            ChannelServices.RegisterChannel(chan, false);

            // Associate the class HelloServer with the URI "SayHello"
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(HelloServer),  //type
                "SayHello",  //uri
                WellKnownObjectMode.SingleCall); //mode
                //WellKnownObjectMode.Singleton);
            
            // Wait until user hits enter to close server
            System.Console.WriteLine("Hit enter to exit...");
            System.Console.ReadLine();

            // Closes socket
            chan.StopListening(null); 
            
            return 0;
        }
    }
}

The client

The client below prompts you for your name, then sends it off to the server. Notice that there's no mention of HelloServer here at all. The code points to the HelloInterface we defined earlier, and the URI refers to the port and the URI we created for the listener. When this call reaches the server, the server checks its own .NET Remoting configuration and finds the class that matches the URI.

C#
// RemoteClient.cs
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteInterface;

namespace RemoteClient
{
    public class Client
    {
        public static int Main(string[] args)
        {
            Console.Title = "RemoteClient";

            // Create an active tcp port
            TcpChannel chan = new TcpChannel();

            // Tell the remoting system to use the channel
            ChannelServices.RegisterChannel(chan, false);
            
            // Create a transparent proxy "obj" for the remote object
            HelloInterface obj = (HelloInterface)Activator.GetObject(
                typeof(RemoteInterface.HelloInterface), // Remote object type
                "tcp://localhost:8084/SayHello"); // Remote object URL

            if (obj == null)
                System.Console.WriteLine("Could not locate " + 
                       "HelloServer type in RemoteServer.exe asembly");
            else
            {
                while (true)
                {
                    System.Console.WriteLine(
                        "What is your name? (just hit enter to quit)");
                    
                    String strName = System.Console.ReadLine();
                    
                    if (String.IsNullOrEmpty(strName))
                        break;
                    
                    // Make method call to remote object
                    Console.WriteLine(obj.HelloMethod(strName));
                }
            }
            return 0;
        }
    }
}

Where to go next

This is almost the simplest .NET Remoting example possible. The RemoteInterface project and the HelloInterface class are not really required; the RemoteClient may reference the RemoteServer assembly directly, and use the HelloServer class in place of the HelloInterface. However, I prefer to define interfaces someplace other than the client or the server.

This article omitted the issue of activation modes, which you had better read about. I also found the examples of configuration files in the Microsoft Help difficult to understand at first. Having read this example, I hope you can see the basic elements that the configuration files control: classes, network endpoints, and protocols.

There is no exception handling in this example. Clearly, you will need to read the help files on each method called to see just what its possible outcomes are and how you should catch and handle them.

History

  • August 28, 2007 - Initial revision.

License

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


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

Comments and Discussions

 
Questiongreat!!! Pin
ElIngenebrio25-Jul-08 7:10
ElIngenebrio25-Jul-08 7:10 
This was THE REAL SIMPLEST EXAMPLE AVAILABLE!!!
I have another question about remoting services, when you want to let only "authenticated users" to consume a service/class, etc. how do you do it? or can you point me some info to google for? i.e. I'm developing an app that was in it's early versions a client server architecture. Now i'm planning to make it service oriented for scalability, i only need to let the classes be consumed by the real users of the client app. Please any help topic will be appreciated. Thanks !!!!!!!
GeneralGr8! Pin
Member 267761426-May-08 14:31
Member 267761426-May-08 14:31 
GeneralExcellent Article Pin
Paul Chin PC9-Sep-07 6:31
Paul Chin PC9-Sep-07 6:31 
GeneralSimple Remote Without Interface Pin
yaniar29-Aug-07 0:10
yaniar29-Aug-07 0:10 
AnswerRe: Simple Remote Without Interface Pin
redredlobster30-Aug-07 2:19
redredlobster30-Aug-07 2:19 
GeneralRe: Simple Remote Without Interface Pin
yaniar30-Aug-07 15:23
yaniar30-Aug-07 15:23 
AnswerRe: Simple Remote Without Interface Pin
redredlobster30-Aug-07 15:46
redredlobster30-Aug-07 15:46 
GeneralRe: Simple Remote Without Interface Pin
yaniar30-Aug-07 19:46
yaniar30-Aug-07 19:46 
GeneralThx Pin
Lasse Offt28-Aug-07 21:16
Lasse Offt28-Aug-07 21:16 

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.