当前位置:编程学习 > C#/ASP.NET >>

C#使用命名管道实现进程间通信

最近做一小程序,其中部分功能用C++,部分功能用C#,两个程序需要互相调用。而且两个程序都是带界面的。以前没有做过C#和C++的相互调用,虽然知道C#可以调用C++的DLL,但是我对C++创建dll不够熟悉,而且感觉将此程序中的C++功能做成dll不方便,于是就想将C#和C++做成两个独立程序,通过进程通信实现互相调用。

从网上找了一篇命名管道实现进程通信的文章,可以按照这个做,顺便把文章转载一下。

以下为转载文章。


本文只是一个测试例子,核心代码是kernel32.dll中的一组windows api函数,这里不深入研究,代码都在codeproject上。

  http://www.codeproject.com/KB/threads/dotnetnamedpipespart1.aspx

  测试效果如下,可以做到aspx和给console app发送消息后得到反馈:

C#中用NamedPipe进程间通信

  console app为服务器端代码如下

usingSystem;  
usingAppModule.InterProcessComm;  
usingAppModule.NamedPipes;  
usingSystem.Threading;  
namespaceServer  
{  
  classProgram  
  {  
    //**c#中用namedpipe进程间通信  
    //**组件代码来自codeproject  
    //**http://www.codeproject.com/KB/threads/dotnetnamedpipespart1.aspx  
    //**下载上面链接中的代码,编译AppModule.InterProcessComm和AppModule.NamedPipes两个dll  
    //**引用这两个dll到本例中,运行如下代码作为服务器端测试  
    //**测试代码byjinjazz(因为原作者的两个测试程序比较复杂,这里简化后供大家参考)  
    staticvoidMain(string[]args)  
    {  
      ServerPipeConnectionPipeConnection=newServerPipeConnection("np-test-by-jinjazz",512,512,5000,false);  
      Console.WriteLine("listening..");  
      while(true)  
      {  
        try 
        {  
          PipeConnection.Disconnect();  
          PipeConnection.Connect();  
          stringrequest=PipeConnection.Read();  
          if(!string.IsNullOrEmpty(request))  
          {  
            Console.WriteLine("get:"+request);  
            PipeConnection.Write("get:"+request);  
            if(request.ToLower()=="break")break;  
          }  
        }  
        catch(Exceptionex)  
        {  
          Console.WriteLine(ex.Message);  
          break;  
        }  
      }  
      PipeConnection.Dispose();  
      Console.Write("pressanykeytoexit..");  
      Console.Read();  
    }  
  }  
} 

  客户端的aspx代码如下

usingSystem;  
usingSystem.Web;  
usingAppModule.InterProcessComm;  
usingAppModule.NamedPipes;  
publicpartialclass_Default:System.Web.UI.Page  
{  
  protectedvoidPage_Load(objectsender,EventArgse)  
  {  
    Response.Write(SendRequest("测试asdf"));  
  }  
  ///<summary>  
  ///测试namepiped客户端  
  ///</summary>  
  ///<paramname="request">发送命令</param>  
  ///<returns>返回数据</returns>  
  stringSendRequest(stringrequest)  
  {  
    stringresponse="";  
    IInterProcessConnectionclientConnection=null;  
    try 
    {  
      clientConnection=newClientPipeConnection("np-test-by-jinjazz",".");  
      clientConnection.Connect();  
      clientConnection.Write(request);  
      response=clientConnection.Read();  
      clientConnection.Close();  
    }  
    catch(Exceptionex)  
    {  
      clientConnection.Dispose();  
      response=ex.Message;  
    }  
    returnresponse;  
  }  
} 

  测试环境为windows vista和windows2003

    
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,