C# - Remoting Client Server Example

This code snippet shows how to create a simple remoting client server program. The code shows how to use remoting to invoke a remote object.
  1. // Create two projects (Client, Server)
  2. // and Add a reference to System.Runtime.Remoting in both.
  3. // Add the ICalculate Interface in both projects.
  4.  
  5.  
  6. // Client.cs
  7. using System;
  8. using System.Runtime.Remoting;
  9. using System.Runtime.Remoting.Channels;
  10. using System.Runtime.Remoting.Channels.Tcp;
  11.  
  12.     class Program
  13.     {
  14.         static void Main(string[] args)
  15.         {
  16.             TcpClientChannel channel = new TcpClientChannel();
  17.             ChannelServices.RegisterChannel(channel, false);
  18.             ICalculate Employee = (ICalculate)Activator.GetObject(typeof(ICalculate), "tcp://localhost:5555/Calculate");
  19.             Console.WriteLine(Employee.Sum(5, 5));
  20.             Console.ReadKey();
  21.         }
  22.     }
  23.  
  24.     public interface ICalculate
  25.     {
  26.         int Sum(int a, int b);
  27.     }
  28.  
  29.  
  30. // Server.cs
  31.  
  32. using System;
  33. using System.Runtime.Remoting;
  34. using System.Runtime.Remoting.Channels;
  35. using System.Runtime.Remoting.Channels.Tcp;
  36.  
  37.   class Program
  38.     {
  39.         static void Main(string[] args)
  40.         {
  41.             TcpServerChannel Channel = new TcpServerChannel(5555);
  42.             ChannelServices.RegisterChannel(Channel,false);
  43.             WellKnownServiceTypeEntry remObj = new WellKnownServiceTypeEntry(typeof(Calculate), "Calculate", WellKnownObjectMode.SingleCall);
  44.  
  45.             RemotingConfiguration.RegisterWellKnownServiceType(remObj);
  46.             Console.WriteLine("Server is running...");
  47.             Console.ReadKey();
  48.  
  49.  
  50.         }
  51.     }
  52.  
  53.   class Calculate : MarshalByRefObject, ICalculate
  54.   {
  55.  
  56.       public int Sum(int a, int b)
  57.       {
  58.           return a + b;
  59.       }
  60.   }
  61.  
  62.   interface ICalculate
  63.   {
  64.       int Sum(int a, int b);
  65.   }

No comments:

Post a Comment