有一個解決方案,其中包括一個Windows服務和一個Windows應用程序,兩者之間需要進行通信。查了下,可以使用多種方法,如Web service(適用於不同系統及跨平臺情況)、.NET Remoting、消息隊列、WCF(集成了前述方法的功能,但太新,不支持Windows2000及以前的系統),其中Remoting可以支持TCP、HTTP、IPC通道的通信,而IPC通道速度快,且僅能供處於同一個系統中的進程間進行通訊,而這正好符合本項目的要求,故決定採用.NET Remoting的IPC方法:
System.Runtime.Remoting程序集(.net組件)和RemoteObject程序集(工程組件)
Client根據約定好的對象地址(URI)“ipc://ServerChannel/RemoteObject”去服務器上訪問RemoteObject對象。Server在收到訪問對象的消息之後,實例化一個RemoteObject對象。當Client得到生成的RemoteObject對象句柄後,調用其Greeting方法,這個調用被傳遞到Server端執行(因爲RemoteObject對象實際上是在Server上),然後返回Greeting方法的結果給Client。
using System;
public class RemoteObject : MarshalByRefObject
{
public RemoteObject()
{
Console.WriteLine("Constructor called");
}
public string Greeting(string name)
{
Console.WriteLine("Greeting called");
return "Hello," + name;
}
}
|
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
public class Server
{
public static void Main(string[]
args)
{
//Instantiate our server channel.
IpcServerChannel channel = new IpcServerChannel("ServerChannel");
//Register the server channel.
ChannelServices.RegisterChannel(channel, false);
//Register this service type.
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject),"RemoteObject", WellKnownObjectMode.SingleCall);
Console.WriteLine("press return to exit");
Console.ReadLine();
}
}
|
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
public class Client
{
public static void Main(string[]
args)
{
//Create an IPC client channel.
IpcClientChannel channel = new IpcClientChannel();
//Register the channel with ChannelServices.
ChannelServices.RegisterChannel(channel, false);
RemoteObject obj = (RemoteObject)Activator.GetObject(typeof(RemoteObject),"ipc://ServerChannel/RemoteObject");
if (obj == null)
{
Console.WriteLine("could not locate server");
return;
}
for (int i = 1; i < 5; i++)
{
Console.WriteLine(obj.Greeting("mmpire"));
}
}
}
|