[ZZ]C#中用NamedPipe进程间通信

本文只是一个测试例子,核心代码是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

来源:blog.csdn    作者:贾涛

你可能感兴趣的:(name)