扩大
缩小

C# 远程调用实现案例

C#远程调用实现案例

 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#的远程调用就实现完成了,这中应用一般在三层架构中应该比较平常使用。至于这种方式的优缺点,在下还不好说,希望有过实际应用的同志给总结一些,谢谢!!!

posted on   禅道  阅读(2198)  评论(0编辑  收藏  举报

编辑推荐:
· 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语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示