C# Remoting Demo

本文深入探讨了.NET Remoting的概念、优势及其在分布式处理中的应用,通过实例展示了如何实现跨应用程序域的远程调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       什么是Remoting,简而言之,我们可以将其看作是一种分布式处理方式。从微软的产品角度来看,可以说Remoting就是DCOM的一种升级,它改善了很多功能,并极好的融合到.Net平台下。Microsoft .NET Remoting 提供了一种允许对象通过应用程序域与另一对象进行交互的框架。这也正是我们使用Remoting的原因。为什么呢?在Windows操作系统中,是将应用程序分离为单独的进程。这个进程形成了应用程序代码和数据周围的一道边界。如果不采用进程间通信(RPC)机制,则在一个进程中执行的代码就不能访问另一进程。这是一种操作系统对应用程序的保护机制。然而在某些情况下,我们需要跨过应用程序域,与另外的应用程序域进行通信,即穿越边界。

       .Net对于远程调用提供了两种方法:Remoting和WebService,那么比起WebService,Remoting更适合于中小型局域网应用,而不适用于企业级的应用。

Remoting具有以下特点:
优点:
1、Tcp通道的Remoting速度非常快
2、虽然是远程的,但是非常接近于本地调用对象
3、可以做到保持对象的状态
4、没有应用程序限制,可以是控制台,winform,iis,windows服务承载远程对象
缺点:
1、不是标准的应用,因此有平台限制
2、脱离iis的话需要有自己的安全机制

下面给出一个Remoting的Demo:

调用对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RemoteObjects
{
    public class RemoteObject : System.MarshalByRefObject
    {
        public RemoteObject()
        {

            Console.WriteLine("New Referance Added!");
        }

        public int GetRdm(int a, int b)
        {
            Random rdm = new Random();
            try
            {
                return rdm.Next(a, b);
            }
            catch
            {
                return 0;
            }
        }
    }
}

Server:

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

namespace RemoteServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Remoting server start...");

            Console.Write("Regist Channel...");
            TcpServerChannel channel = new TcpServerChannel(8201);
            ChannelServices.RegisterChannel(channel, true);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall);
            Console.WriteLine("OK");
            Console.ReadKey(true);

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}


Client:

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

namespace RemoteClient
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelServices.RegisterChannel(new TcpClientChannel(), true);
            RemoteObject remoteobj = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "tcp://localhost:8201/RemoteObject");
            Console.WriteLine("[1, 100) => " + remoteobj.GetRdm(1, 100).ToString());
            Console.ReadLine();
            Console.ReadKey(true);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值