參考文章:https://www.microsoft.com/china/msdn/library/architecture/architecture/architecturetopic/BuildSucApp/BSAAsecmodsecmod29.mspx?mfr=true
1.首先寫接口定義遠程對象需要操作的方法,這個接口定義在單獨的類庫,供windowsservice引用和遠程客戶端引用.
public interface IRemoteObjectMethod
{
void DoSth();
}
2.然後建立windows service 工程,添加實現遠程對象接口的類.
public class RemoteObject : MarshalByRefObject, IRemoteObjectMethod
{
public RemoteObject()
{}
// 添加方法的具體實現
}
3.添加註冊遠程對象配置節到app.config.
如下:
<system.runtime.remoting>
<application name="ServerToClientService">
<service>
<wellknow type="DownLoaderService.MarshalDownSyncObject, DownLoaderService" objectUri="DownSyncObject" mode="singlecall"/>
</service>
<channels>
<channel ref="tcp" port="6767">
<serverProviders>
<formatter ref="binary"/>
</serverProviders>
</channel>
</channels>
</application>
</system.runtime.remoting>
4.在windows service的開始方法裏面添加註冊遠程對象的代碼.
protected override void OnStart(string[] args)
{
RemotingConfiguration.Configure (AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
5.安裝windows服務.這個就不必詳細寫了.
至此,windows service的部分已經完成,接下來的都是在遠程客戶機上的操作.
6.添加獲取遠程對象的類和配置文件.
public class RemoteObjectFactory
{
// 承載遠程對象的服務名稱
private static string svc_Name = ConfigurationSettings.AppSettings["ServiceName"];
// 遠程服務所在的ip地址
private static string svc_ipAddress = ConfigurationSettings.AppSettings["ServiceIP"];
// 遠程對象註冊時的端口號
private static int svc_port = int.Parse(ConfigurationSettings.AppSettings["ServicePort"]);
// 遠程對象的標識
private static string svc_objectUri = ConfigurationSettings.AppSettings["ObjectUri"];
// 遠程連接通道的類型
private static string channelType = ConfigurationSettings.AppSettings["ChannelType"];
public static IRemoteObjectMethod GetServerSyncObject()
{
string url = channelType + "://" + svc_ipAddress + ":" + svc_port.ToString() + "/" + svc_Name + "/" + svc_objectUri;
IRemoteObjectMethod obj = (IRemoteObjectMethod)Activator.GetObject (typeof (IRemoteObjectMethod), url);
if (obj == null)
{
throw new Exception("Service not exists or Remoteobject not exists!");
}
return obj;
}
}
創建遠程對象獲取的方法,並在app.config添加相應的配置項.
7.遠程客戶端調用
IRemoteObjectMethod remoteObject = RemoteObjectFactory.GetServerSyncObject();
remoteObject.DoSth();
這樣似乎可以比較輕鬆的實現遠程方法的調用:)