利用IPC通道進行進程間通信(C#)

有一個解決方案,其中包括一個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#高級編程>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章