C#實現遠程調用主要用到“System.Runtime.Remoting”這個東西。下面從三個方面給於源碼實例。
·服務端:

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting;

namespace RemoteSample

{

class server

{

static int Main(string[] args)

{

//注冊通道

TcpChannel chan = new TcpChannel(8085);

ChannelServices.RegisterChannel(chan);

string sshan = chan.ChannelName;

System.Console.WriteLine(sshan);

//注冊遠程對象,即激活.

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteSample.HelloServer), "SayHello", WellKnownObjectMode.SingleCall);

System.Console.WriteLine("Hit <ennter> to exit...");

System.Console.ReadLine();

return 0;

}

}

}
·客戶端:

using System.Runtime.Remoting.Channels.Tcp;

using System.Runtime.Remoting.Channels;

namespace RemoteSample

{

public class Client

{

public static int Main(string[] args)

{

TcpChannel chan = new TcpChannel();

ChannelServices.RegisterChannel(chan);

HelloServer obj =(HelloServer)Activator.GetObject(typeof(HelloServer), "tcp://localhost:8085/SayHello");

if (obj == null)

System.Console.WriteLine("Could not locate server");

else Console.WriteLine(obj.HelloMethod("Caveman"));

return 0;

}

}

}
·遠程對象:(重點),該對象是一個dll的程序集,同時被客戶端和服務器端引用。

namespace RemoteSample

{

//客戶端獲取到服務端的對象實際是一個對象的引用,因此必須繼承:MarshalByRefObject

public class HelloServer : MarshalByRefObject

{

public HelloServer()

{

Console.WriteLine("HelloServer activated");

}

public String HelloMethod(String name)

{

Console.WriteLine("Hello.HelloMethod : {0}", name);

return "Hi there " + name;

}

//說明1:在Remoting中的遠程對象中,如果還要調用或傳遞某個對象,例如類,或者結構,則該類或結構則必須實現串行化Attribute[SerializableAttribute]:

//說明2:將該遠程對象以類庫的方式編譯成Dll。這個Dll將分別放在服務器端和客戶端,以添加引用

//說明3:在Remoting中能夠傳遞的遠程對象可以是各種類型,包括復雜的DataSet對象,只要它能夠被序列化

}
注意上述代碼的注釋,由於遠程服務的特殊性,因此在此做了詳細的批注,怕大伙不理解。
OK。C#的遠程調用就實現完成了,這中應用一般在三層架構中應該比較平常使用。至於這種方式的優缺點,在下還不好說,希望有過實際應用的同志給總結一些,謝謝!!!