有一个解决方案,其中包括一个Windows服务和一个Windows应用程序,两者之间需要进行通信。查了下,可以使用多种方法,如Web service(适用于不同系统及跨平台情况)、.NET Remoting、消息队列、WCF(集成了前述方法的功能,但太新,不支持Windows2000及以前的系统),其中Remoting可以支持TCP、HTTP、IPC通道的通信,而IPC通道速度快,且仅能供处于同一个系统中的进程间进行通讯,而这正好符合本项目的要求,故决定采用.NET Remoting的IPC方法:


开发平台为Visual Studio 2005,.NET framework版本为2.0

1、 建立空白解决方案

2、 添加两个新工程项目Console Application:Server和Client

3、 添加一个Class Library:RemoteObject

4、 三个项目的源代码Server.cs、Client.cs、RemoteObject.cs分别附后

5、 在Server和Client项目的引用中添加两个程序集:

System.Runtime.Remoting程序集( .net组件)和RemoteObject程序集(工程组件)

6、 生成两个工程之后,双击打开 Server程序,再打开Client,可以看到两者通信。

7、 程序逻辑很简单:

Client根据约定好的对象地址(URI)“ ipc://ServerChannel/RemoteObject”去服务器上访问 RemoteObject对象。Server在收到访问对象的消息之后,实例化一个RemoteObject对象。当Client得到生成的RemoteObject对象句柄后,调用其Greeting方法,这个调用被传递到Server端执行(因为RemoteObject对象实际上是在Server上),然后返回Greeting方法的结果给Client。

8、 简言之,即完成了Client进程访问Server进程的一个对象,并调用此对象的方法的任务。

9、 源代码:

RemoteObject.cs

using System;
public class RemoteObject : MarshalByRefObject
{
public RemoteObject()
{
Console.WriteLine("Constructor called");
}
public string Greeting(string name)
{
Console.WriteLine("Greeting called");
return "Hello," + name;
}
}

Server.cs

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();
}
}

Client.cs

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"));
}
}
}

Server输出:

press return to exit

Constructor called

Greeting called

Constructor called

Greeting called

Constructor called

Greeting called

Constructor called

Greeting called

Client输出:

Hello,mmpire

Hello,mmpire

Hello,mmpire

Hello,mmpire


参考:<C#高级编程>