C#构建一个简单的分布式应用程序(.net远程处理)

来源:互联网 发布:深入浅出mysql 编辑:程序博客网 时间:2024/04/29 22:42

由3个.NET程序集构成:

SimpleRemotingAsm.dll

SimpleRemoteObjectServer.exe

SimpleRemoteObjectClient.exe

下面是代码

SimpleRemotingAsm控制台程序

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

namespace SimpleRemotingAsm
{
  
        //这个类型在被远程访问时会以引用方式封送(MBR)
        public class RemoteMessageObject : MarshalByRefObject
        {
            public RemoteMessageObject()
            {
                Console.WriteLine("Constructing RemoteMessageObject!");


            }
            //这个方法从调用那里获取一个输入字符串
            public void DisplayMessage(string msg)
            {
                Console.WriteLine("Message is:{0}", msg);
            }
            //这个方法把值返回调用方
            public string ReturnMessage()
            {
                return "Hello from the server";
            }
        }
  
}

 

SimpleRemoteObjectServer控制台程序

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting;

namespace SimpleRemoteObjectServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*****SimpleRemoteObjectServer started!******");
            Console.WriteLine("Hit enter to end");

            //注册一个新的信道
            HttpChannel c = new HttpChannel(32469);
            ChannelServices.RegisterChannel(c, false);

            //注册一个WKO类型,使用单例激活

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(SimpleRemotingAsm.RemoteMessageObject), "RemoteMsgObj.soap", WellKnownObjectMode.Singleton);
            Console.ReadLine();
        }
    }
}

SimpleRemoteObjectClient控制台程序

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting;
using SimpleRemotingAsm;

namespace SimpleRemoteObjectClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*****SimpleRemoteObjectClient started!******");
            Console.WriteLine("Hit enter to end");
            //注册一个新的信道
            HttpChannel c = new HttpChannel();
            ChannelServices.RegisterChannel(c,false);

            //注册一个WKO类型
             object remoteObj = Activator.GetObject(typeof(SimpleRemotingAsm.RemoteMessageObject),"http://localhost:4313/RemoteMsgObj.soap");
            //现在使用远程对象
             RemoteMessageObject simple = (RemoteMessageObject)remoteObj;
             simple.DisplayMessage("Hello from the client");
             Console.WriteLine("Server says:{0}",simple.ReturnMessage());
             Console.ReadLine();

        }
    }
}

原创粉丝点击