How To Use Remote Procedure Call (RPC) in C#:

Server Codes

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

namespace RPCServer
{
public class MathService : MarshalByRefObject
{

public int Add(int a, int b)
{
Console.WriteLine(“Received Add request”);
return a + b;
}

public int Subtract(int a, int b)
{
Console.WriteLine(“Received Subtract request”);
return a – b;
}
}

class Program
{
static void Main(string[] args)
{
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(MathService),
“MathService”,
WellKnownObjectMode.SingleCall
);
Console.WriteLine(“Press enter to exit”);
Console.ReadLine();
}
}
}

Client Code

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

namespace RPCCLient
{
class Program
{
static void Main(string[] args)
{
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel, false);

MathService service = (MathService)Activator.GetObject(
typeof(MathService),
“tcp://localhost:8080/MathService”
);

Console.WriteLine(“5 + 3 = ” + service.Add(5, 3));
Console.WriteLine(“5 – 3 = ” + service.Subtract(5, 3));

Console.WriteLine(“Press enter to exit”);
Console.ReadLine();
}
}
}

This example creates a simple math service that can perform addition and subtraction operations, and makes it available over the network using the TCP protocol. The MathService class is decorated with the MarshalByRefObject attribute, which makes it possible to call its methods from a remote client.

The RPCServer project contains the code for the server, which registers the MathService class with the .NET remoting framework and makes it available over the network. The RPCCLient project contains the code for the client, which uses the .NET remoting framework to call methods on the remote MathService instance.

Scroll to Top