Remoting技术使用配置文件示例

1、创建类库工程RemotableType.dll (提供remotable 类型)。

RemotableType.cs

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

namespace MyRemotableType
{
    public class RemotableType : MarshalByRefObject
    {
        private string _internalString = "This is the RemotableType.";
        public string RemoteTypeMethod()
        {
            return _internalString;
        }
    }
}

2、创建服务器端程序RemoteTypeHost.exe。注意添加System.Runtime.Remoting.dll 和

  RemotableType.dll 的引用。

Listener.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using MyRemotableType;

namespace RemoteTypeHost
{
    class Listener
    {
        public static void Main()
        {
            RemotingConfiguration.Configure("RemoteTypeHost.exe.config", false);
            Console.WriteLine("Listening for requests. Press Enter to exit...");
            Console.ReadLine();
        }
    }
}

创建服务器端配置文件 RemoteTypeHost.exe.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <service>
        <wellknown
           mode="Singleton"
           type="MyRemotableType.RemotableType, RemotableType"
           objectUri="RemotableType.soap"
            />
      </service>
      <channels>
        <channel ref="http" port="8989"/>
      </channels>
    </application>
  </system.runtime.remoting>
</configuration>

3、创建客户端程序 RemoteClient.exe。注意添加System.Runtime.Remoting.dll 和

  RemotableType.dll 的引用。

Client.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using MyRemotableType;

namespace RemoteClient
{
    class Client
    {
        public static void Main()
        {
            RemotingConfiguration.Configure("RemoteClient.exe.config", false);
            RemotableType remoteObject = new RemotableType();
            Console.WriteLine(remoteObject.RemoteTypeMethod());
            Console.Read();
        }
    }
}

创建客户端配置文件RemoteClient.exe.config :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <client>
        <wellknown
           type="MyRemotableType.RemotableType, RemotableType"
           url="http://shuzh:8989/RemotableType.soap"
            />
      </client>
    </application>
  </system.runtime.remoting>
</configuration>

运行方法:

客户端程序:RemoteClient.exe、RemoteClient.exe.config 、RemotableType.dll;

服务器端程序:RemoteTypeHost.exe、RemoteTypeHost.exe.config、RemotableType.dll;

客户端、服务器端均可以分布在网络可见的任何计算机上。

启动服务器端,启动客户端。

使用配置文件的优点很明显:

你可以随时随地、随心所欲改变配置,而无需重新编译程序。

比如,你可将服务器端配置文件中端口改为9999,

客户端配置文件当然要做同步改动。

启动服务器端;启动客户端;你会发现程序运行良好。

注意:wellknown 中 type属性为:<namespace>.<class>, <assembly>

原文地址:https://www.cnblogs.com/MayGarden/p/1640637.html