Click here to Skip to main content
Click here to Skip to main content

Just .NET Remoting

, 28 Aug 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

// 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.

// 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.

// 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.

// 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)

Share

About the Author

redredlobster

United States United States
No Biography provided

Comments and Discussions

 
Questiongreat!!! PinmemberElIngenebrio25-Jul-08 7:10 
GeneralGr8! PinmemberMember 267761426-May-08 14:31 
GeneralExcellent Article PinmemberPaul Chin PC9-Sep-07 6:31 
GeneralSimple Remote Without Interface Pinmemberyaniar29-Aug-07 0:10 
AnswerRe: Simple Remote Without Interface Pinmemberredredlobster30-Aug-07 2:19 
GeneralRe: Simple Remote Without Interface Pinmemberyaniar30-Aug-07 15:23 
AnswerRe: Simple Remote Without Interface Pinmemberredredlobster30-Aug-07 15:46 
GeneralRe: Simple Remote Without Interface Pinmemberyaniar30-Aug-07 19:46 
OK. Thanks for the info. By the way, it's a great article Smile | :)
GeneralThx PinmemberWb-FreeKill28-Aug-07 21:16 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 28 Aug 2007
Article Copyright 2007 by redredlobster
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid