A simple Remoting example in C#

After looking in vain for an easy example to understand the basics of remoting, I decided to write one myself. I found one or two useful articles, but they had syntax errors and left a lot for the reader to fill in. My example needs no tweaking and can be used as is. For simplicity, I use only one machine. The server and the client reside on the same machine.

Problem statement:

TicketServer holds information about the ticket status of a movie theater. A client needs to know the status of a ticket. Establish a connection between the client and the server so that client gets the information needed.

Solution:

A method called GetTicketStatus is defined in the server space. This method returns the status of the ticket. The server publishes this method which can be used by any client. The server listens to port 9998 over TCP. The client invokes the published method and gets the ticket status.

Implementation:

An interface MovieTicketInterface is defined which contains the GetMovieTicket method signature. This interface is implemented by MovieTicket class. The method GetMovieTicket is also implemented.

The server TicketServer registers the MovieTicket class as a remoting service. It listens to the port 9998 and waits for communication from any client.

The client creates an object of type MovieTicketInterface as a remoting object. As a part of this step, the communication between the server and the client over TCP on port number 9998 is established. It then invokes the method GetTicketStatus and gets the status.

Source code:

Server part:

1. Create a Console Application named TicketServer.
2. Add System.Runtime.Remoting as a reference to the project.
3. Replace the existing code in Class.cs with the following code and build the project.

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{
static void Main(string[] args)
{
TicketServer();
}

static void TicketServer()
{
Console.WriteLine("Ticket Server started...");

TcpChannel tcpChannel = new TcpChannel(9998);
ChannelServices.RegisterChannel(tcpChannel);

Type commonInterfaceType = Type.GetType("MovieTicket");

RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,
"MovieTicketBooking", WellKnownObjectMode.SingleCall);

System.Console.WriteLine("Press ENTER to quitnn");
System.Console.ReadLine();

}

}

public interface MovieTicketInterface
{
string GetTicketStatus(string stringToPrint);
}

public class MovieTicket : MarshalByRefObject, MovieTicketInterface
{
public string GetTicketStatus(string stringToPrint)
{
string returnStatus = "Ticket Confirmed";
Console.WriteLine("Enquiry for {0}", stringToPrint);
Console.WriteLine("Sending back status: {0}", returnStatus);

return returnStatus;
}
}

Client side:

1. Create a Console Application named Client.
2. Add System.Runtime.Remoting and Server.exe [See Note 1] as references to the project.
3. Replace the existing code in Class.cs with the following code and build the project.


using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class MyClient
{
public static void Main()
{
TcpChannel tcpChannel = new TcpChannel();
ChannelServices.RegisterChannel(tcpChannel);

Type requiredType = typeof(MovieTicketInterface);

MovieTicketInterface remoteObject = (MovieTicketInterface)Activator.GetObject(requiredType,
"tcp://localhost:9998/MovieTicketBooking");

Console.WriteLine(remoteObject.GetTicketStatus("Ticket No: 3344"));
}
}

Execution:

1. Execute Server.exe
2. Execute Client.exe

You will see the appropriate messages on the client side and the remote side.

Note 1: If you are using Visual Studio 2003, you cannot add a reference to an exe file. Make a copy of Server.exe, rename it to Server.dll and this can be added as a reference in your client project.

About these ads

79 thoughts on “A simple Remoting example in C#

  1. WAS says:

    Tried this exactly and it does not work. Type.GetType(“MovieTicket”); return null. Am I missing something?

  2. generally says:

    I tried out these steps and it works for me. Did you copy the code or did type it out? Check if you have put MovieTicketInterface or MovieTicket in a namespace. It shouldn’t be within any namespace.

  3. swapna says:

    i tried.But the following errors are coming while i execute the client.
    The type or namespace “MovieTicketInterface” could not be found.
    The type or namespace “remoteObject” could not be found.

    Kindly give me a solution

  4. generally says:

    Swapna,

    I am sure you missed the step 2 on the client side. You need to add these two references:
    1. System.Runtime.Remoting
    2. Server.exe

    I think you missed adding Server.exe as a reference in your Client project. Correct this and it should work.

  5. Ashoka says:

    Hi

    Thanks for the example..

    Can you also post the things that should be learnt next on the Remoting topic, so that we can know what else can be done using Remoting.

    Thanks

  6. generally says:

    Sure, Ashoka. As you may have read in my post, remoting is a new toping for me too. I am yet to use it in any real life application. As and when I realize its applications, I will surely put it up on the blog.

  7. R.K.T. Ashoka says:

    Thanks..

  8. ranjan says:

    When I’m adding the server (server.exe) reference to the client code. I’m getting the error as below.
    The ticketserver.exe can’t be added, since it is not a valid dll or com component.

    Can you please help me out .

    Thanks,
    Ranjan.


    Ranjan,

    How did you add the reference? You need to right click on References->Add Reference->Browse. Locate your Server.exe and click on Add. This should go through without any problem.

  9. ranjan says:

    As I’m new to ramoting concept I was trying the above example.
    I had have the issue while adding the server reference to the client.

    I appreciate for the fast response….

    Thanks,
    Ranjan.

  10. generally says:

    Ranjan,

    How did you add the reference? You need to right click on References->Add Reference->Browse. Locate your Server.exe and click on Add. This should go through without any problem.

  11. ranjan says:

    Hi,
    Thanks for the reply.

    Yeah I did the same away as you have explained above.
    The Server.exe is located at C :\inetpub\wwwroot\testdg\server\bin\debug\server.exe
    When browse to add the server.exe, I’m getting the message “This is not a valid assembly or COM component. Only assemblies with extension dll or COM components can be referenced”.

    According to error info, we can’t reference to exe (i.e means we can only refer dll or COM component).

    Can you please suggest me further.

    Thanks,
    Ranjan.

  12. generally says:

    Ranjan, I tried adding the reference and I didn’t face any problem. Which version of Visual Studio are you using? I am using VS 2005.

  13. ranjan says:

    I’m using vs 2003.

  14. generally says:

    Ranjan, I found a solution to your problem. Go to the directory where Server.exe is there. Make a copy of that and rename it to Server.dll. You can add a reference to this in your Client project. I just tried this with VS 2003 and it works.

  15. Daran says:

    Thanks. This example showed exactly what I wanted to know without getting lost in complexity. Btw I solved the reference problem by moving the interface to a separate source code file and linking that to both projects as shown in http://blogs.msdn.com/davidklinems/archive/2006/11/29/quick-tip-sharing-code-between-multiple-projects-in-visual-studio-2005.aspx

  16. generally says:

    Thanks for the link, Daran. I will go through that.

  17. Jason says:

    so what is the reason for adding a reference to the server assembly? in a commercial application it may be a bad idea to include the server executable along with the client.

    how would one resolve this without needing a reference to the server?

  18. anaamica says:

    Jason,
    I forgot to add this information in my post. In an actual application, one will not add a reference to the server exe, but a reference to the interface implemented by server.exe will be added.

    • mukesh says:

      can you please share the sample application with your post”one will not add a reference to the server exe, but a reference to the interface implemented by server.exe will be added.”

    • mukesh says:

      Hi Anaamica
      I want to use the same the server.exe on php web application so i want a common interface that i can use both on web based application and on window bases application.

  19. Naveen Mandava says:

    Hi i worked with thisexample and added the sever.exe still I am gettting the errror ..could u make me free form this error..

    Error 2 The type or namespace name ‘MovieTicketInterface’ could not be found (are you missing a using directive or an assembly reference?) C:\Users\mandava\Documents\Visual Studio 2005\Practice\projects\Remoting\Client\Client\Program.cs 14 31 Client

  20. Anaamica says:

    Naveen, it’s hard to say what the reason could be without looking at your code. My guess is you need to add ‘using ‘ statement so that it recognizes the type.

  21. Naveen Mandava says:

    Hi Anaamica
    The same code which was displayed in this article I used …ya I added USing statements ..Perfectly…I am not exact with adding server.exe..

  22. Lucas says:

    TO Naveen Mandava.
    I had the same problem wint VS2003, but i solved it. Follow this steps:
    1. In the MyClient.cs class, comment all the code in Main() method.
    2. Build the client project. You shouldnt have any error.
    3. Add the server.dll file (rename .exe to .dll)
    4. Discomment Main() method in MyClient class and build. Now y shouldnt have any error.

    hope it helps ;)

  23. MP09IND says:

    Good example thanks………….

  24. Nick says:

    Hi,

    My question is regarding the client-server arch:

    Does remoting automatically start the server when the client attempts to make calls?

    I ask this because I was able to start the client program, and have it return information without ever starting the Server.exe file.

    Any insight would be appreciated.

    Nick

  25. Ranjit says:

    Hi,
    This example worked for me. But here server and client relied in the same machine. Can you give an example of interacting remote object across network or machine. Thanks for the effort and i’m waiting for your reply.

  26. muneer says:

    Hi All,

    Can you tell me what is the alternative for

    System.Runtime.Remoting.Channels.Tcp;

    in VS 2008 ?

    Muneer

  27. Peter says:

    Thank you posted example!

  28. jaswinder says:

    This is good example and works fine.

  29. Peter says:

    Problem you
    “commonInterfaceType” not null

    This is :
    RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,
    “MovieTicketBooking”, WellKnownObjectMode.SingleCall);

  30. spgn says:

    I managed to use it with namespaces when I changed
    Type.GetType(“MovieTicket”)

    to
    Type.GetType(“TicketServer.MovieTicket”);

    TicketServer being the namespace of the server, where the MovieTicket class resides.

  31. spgn says:

    And thanks a lot for the example by the way! :)

  32. spgn says:

    Another comment:
    When adding a reference to the Server.exe file, changes in the server interface are not immediately seen in the client application. Adding a reference to the server project instead solves the issue.

  33. Off course its a very useful example for remoting beginners, Nice work.

    Slightly I was altered the code and worked fine with visual studio 2008

    See the code below

    ////////////////////////
    Server Code Starts
    ///////////////////////
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;

    namespace Server
    {
    class Program
    {
    static void Main(string[] args)
    {
    TicketServer();
    }

    static void TicketServer()
    {
    Console.WriteLine(“Ticket Server started…”);

    TcpChannel tcpChannel = new TcpChannel(9998);
    ChannelServices.RegisterChannel(tcpChannel);
    Type commonInterfaceType = Type.GetType(“Server.MovieTicket”);
    RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,”MovieTicketBooking”, WellKnownObjectMode.SingleCall);

    System.Console.WriteLine(“Press ENTER to quit”);
    System.Console.ReadLine();
    }

    }
    public interface MovieTicketInterface
    {
    string GetTicketStatus(string stringToPrint);
    }
    public class MovieTicket : MarshalByRefObject, MovieTicketInterface
    {
    public string GetTicketStatus(string stringToPrint)
    {
    string returnStatus = “Ticket Confirmed”;
    Console.WriteLine(“Enquiry for {0}”, stringToPrint);
    Console.WriteLine(“Sending back status: {0}”, returnStatus);
    return returnStatus;
    }
    }
    }

    ///////////////////////////////////
    Server Code Ends
    ///////////////////////////////////

    ///////////////////////////////////
    Client Code Starts
    ///////////////////////////////////

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using Server;

    namespace Client1
    {
    //class Program
    //{
    // static void Main(string[] args)
    // {
    // }
    //}
    class MyClient
    {
    public static void Main()
    {
    TcpChannel tcpChannel = new TcpChannel();
    ChannelServices.RegisterChannel(tcpChannel);

    Type requiredType = typeof(MovieTicketInterface);

    MovieTicketInterface remoteObject = (MovieTicketInterface)Activator.GetObject(requiredType,
    “tcp://localhost:9998/MovieTicketBooking”);

    Console.WriteLine(remoteObject.GetTicketStatus(“Ticket No: 3344″));
    }
    }

    }

    ////////////////////////////////
    Client Code Ends
    ////////////////////////////////
    NOTE
    1. Both Are Visual C# Console Projects
    2. You are requested to add reference to System.Runtime.Remoting in Visual studio 2008
    3. I was copied Server.exe from server project’s bin\debug folder to Client Application’s bin\debug folder and renamed as Server.dll then added a reference to Client Application project

    Start Server and Client applications

  34. Type commonInterfaceType = Type.GetType(“SecondTicketServerMote.MovieTicket”);

    where SecondTicketServerMote is my friggin Namespace TYPE in get type is specific and requires COMPLETE Name space pathing to get the object even in the same damn namespace ….pissed me off for all of three minutes

  35. PRMARJORAM says:

    Excellent example, thanks very much worked first time. No fuss just straight to the point of how to setup a remote connection between client and server. Again the fact they are on the same machine in the example aids its simplicity.

    I have extended it to passing and receiving objects and it seems alls you have to do to make this possible is the class of the objects needs to inherit from MarshalByRefObject

  36. pavan says:

    Hi,

    I have one windows application called Client, another one console application called server, and 3rd one is class library.

    In windows application, I have 5 forms and implemented client code.
    In console application I implemented server code i.e actual logic.
    In class library I have interfaces for server classes.

    But my question is how implementing the remoting for windows application and console application?

    Thanks,
    Pavan

  37. I think people are missing the NameSpace thing………..look into that…….

    Means look into your code and suggested sample code………..

    Hope my this comment will make happy to lot of users who are facing trouble in given sample application.

  38. Eric says:

    Just started this article but it looks great. Really, really like the approach — clearly stating a concrete problem then showing how it’s done. Thank you.

  39. Tailsx says:

    Thanx mate worked perfectly no problems what so ever, clearly explained and nice work (Y)

  40. Tailsx says:

    @ Sachin Tiwari no it isn’t missing anything
    1. Create a Console Application named TicketServer.
    2. Add System.Runtime.Remoting as a reference to the project.
    3. Replace the existing code in Class.cs with the following code and build the project.

    it says everything :S do as told and it will work

  41. anaamica says:

    Tailsx, I am glad it worked for you.

  42. jhili says:

    I have some problem in client
    Error 2 The type or namespace name ‘TrainTicketInterface’ could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\Prasanta.PRASANTA-LAPY\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication1\Program.cs 17 40 ConsoleApplication1
    these are the errors
    1 warning also there as below
    Warning 1 ‘System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(System.Runtime.Remoting.Channels.IChannel)’ is obsolete: ‘Use System.Runtime.Remoting.ChannelServices.RegisterChannel(IChannel chnl, bool ensureSecurity) instead.’ C:\Documents and Settings\Prasanta.PRASANTA-LAPY\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication1\Program.cs 15 13 ConsoleApplication1
    please help me out

    Error 3 The type or namespace name ‘TrainTicketInterface’ could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\Prasanta.PRASANTA-LAPY\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication1\Program.cs 19 13 ConsoleApplication1
    Error 4 The type or namespace name ‘TrainTicketInterface’ could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\Prasanta.PRASANTA-LAPY\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication1\Program.cs 19 50 ConsoleApplication1

    • I donno how to thanks says:

      for people that get err on Client
      u have to add Refrence to your server
      how ?
      right click on Client program–> addreference —> Brows — > [projects\ticketseerver]\ticketserver\bin\debug
      select the exe

  43. I donno how to thanks says:

    for people that get err on Client
    u have to add Refrence to your server
    how ?
    right click on Client program–> addreference —> Brows — > [projects\ticketseerver]\ticketserver\bin\debug
    select the exe

  44. KiNGPiN says:

    Love you man .. u just saved my day :)

    was abt to bang my head to the wall :p

  45. gumbald says:

    Lovely example, gave me a good base to start, thanks!

  46. David says:

    Thank you for the lesson, this was great !

  47. ergus says:

    It’s Works fine!

    Thanks

    Alberto

  48. Saladin says:

    Just what I was looking for!
    Thank you so much

  49. Arno says:

    Works great for me, too, after I dropped the namespaces. I have even separated out the classes to watch it work across the network.

    I real-world use for me is that I put the servers (I call them listeners) on the network and I query the remote machines’ status, file existence, remote commands, etc.

    Thanks for the examples and the help! :-)

  50. Zia says:

    this is not working.. where is the server.exe file? is it the output of the compiled TicketServer app? or different? There is only TicketServer.exe in the TicketServer bin & debug folder

  51. Renuka Bitla says:

    If anyone is getting null exception please use the following code in server program
    RemotingConfiguration.RegisterWellKnownServiceType(typeof(MovieTicket), “MovieTicketBooking”, WellKnownObjectMode.SingleCall);

  52. TheYarb says:

    Visual Studio 2010 is yielding some problems.

    1st, System.Runtime.Remoting.Channels.Tcp shows as a bad namespace because Channels has no subgroups in Intellisence.

    So I checked references, System.Runtime.Remoting is not listed as a reference. When I went to add it, there is no System.Runtime choice except System.Runtime.Serialization.

    Please advise.

  53. Deepu says:

    Very thanks and I request you to send me more code examples in C,c++,c#.NET to my mail ID
    deepup226@gmail.com

  54. vikas says:

    thanks for codez
    plz mujhe yeh batao ki client jb window application se banayenge to interface kaise add karenge!!

  55. Javaid says:

    Too simple and too good, love that :)

  56. It?s really a nice and useful piece of information. I?m glad that you simply shared this helpful information with us. Please stay us informed like this. Thanks for sharing.

  57. Yaroslav says:

    Nice example.
    But, what we have to do for make some actions with object on the server?
    We haven’t access to instance of MovieTicket.
    Also, we can’t make custom constructor for it.

  58. Dayanand says:

    TcpChannel tcpChannel = new TcpChannel();

    ChannelServices.RegisterChannel(tcpChannel);

    why do u need above two lines in client side???
    even without above statements everything works fine :)

  59. raghubir says:

    Hi Friend,
    You have done great job for this example. I have done everything as u have mentions but when i execute client.exe it gives me the following error.
    Error-: No connection could be made because the target machine actively refused it 127.0.0.1:9998.

    Please revert me, what can i do to remove this error in order to successfully execution of my program ?

  60. simil says:

    nice article….very simple to implement….thx a lot..!!

  61. prasad bhagat says:

    iam pursuing asp.net now but i need a sample messenger usnig remoting any body provide to me with design also pls provide to me iam in c# i mis this class so …..pls
    i u have soltuion pls send me to bhagatprasad8@gmail.com ………..

  62. swazi15 says:

    THANK YOU :O :). I have been looking allllll over the net for a simple and effective example of remoting. This perfectly demonstrates the concepts of remoting, just what i needed thank you so so so much. Works 110% for me :) :).

  63. shanthig says:

    thanks lot…

  64. Lakshmi says:

    I was not able to add the reference server.exe, i am using VS2010.. where is it located and how to add it..?? plz help.

  65. Alexander says:

    Lakshmi, look for TicketServer.exe.

    Generally thought, isnt that whole TicketServer.exe referencing thing a bit odd? .NET Remoting aims using a RemoteObject without maintaining it on a local machine. That TicketServer including his MovieTicket Object is normally not local and therefore cant be referenced via “Add reference”.

  66. BipinBaglung says:

    Suppose i sent a list of ticket id (with 10 tickets) and the server has to process the status of all tickets and return final result. Server processes for status of each ticket which takes some time. Now before sending final result , server has to send “I am processing 1st ticket …., 2nd ticket” like message when it starts processing new ticket and client machine has to handle it. Can you provide any idea/example to handle this?

    Thanks,
    BipinBaglung

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: