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#的远程调用就实现完成了,这中应用一般在三层架构中应该比较平常使用。至于这种方式的优缺点,在下还不好说,希望有过实际应用的同志给总结一些,谢谢!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决