本文只是一個測試例子,核心代碼是kernel32.dll中的一組windows api函數,這裡不深入研究,代碼都在codeproject上。
http://www.codeproject.com/KB/threads/dotnetnamedpipespart1.aspx
測試效果如下,可以做到aspx和給console app發送消息後得到反饋:
console app為服務器端代碼如下
using System; using AppModule.InterProcessComm; using AppModule.NamedPipes; using System.Threading; namespace Server { class Program { //**c#中用namedpipe進程間通信 //**組件代碼來自codeproject //**http://www.codeproject.com/KB/threads/dotnetnamedpipespart1.aspx //**下載上面鏈接中的代碼,編譯AppModule.InterProcessComm和AppModule.NamedPipes兩個dll //**引用這兩個dll到本例中,運行如下代碼作為服務器端測試 //**測試代碼by jinjazz(因為原作者的兩個測試程序比較復雜,這裡簡化後供大家參考) static void Main(string[] args) { ServerPipeConnection PipeConnection = new ServerPipeConnection("np-test-by-jinjazz", 512, 512, 5000, false); Console.WriteLine("listening.."); while (true) { try { PipeConnection.Disconnect(); PipeConnection.Connect(); string request = PipeConnection.Read(); if (!string.IsNullOrEmpty(request)) { Console.WriteLine("get:" + request); PipeConnection.Write("get:" + request); if (request.ToLower() == "break") break; } } catch (Exception ex) { Console.WriteLine(ex.Message); break; } } PipeConnection.Dispose(); Console.Write("press any key to exit.."); Console.Read(); } } }
客戶端的aspx代碼如下
using System; using System.Web; using AppModule.InterProcessComm; using AppModule.NamedPipes; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(SendRequest("測試asdf")); } /// <summary> /// 測試namepiped客戶端 /// </summary> /// <param name="request">發送命令</param> /// <returns>返回數據</returns> string SendRequest(string request) { string response=""; IInterProcessConnection clientConnection = null; try { clientConnection = new ClientPipeConnection("np-test-by-jinjazz", "."); clientConnection.Connect(); clientConnection.Write(request); response=clientConnection.Read(); clientConnection.Close(); } catch (Exception ex) { clientConnection.Dispose(); response = ex.Message; } return response; } }
測試環境為windows vista和windows2003