2009-05-21 83 views
16

我有兩個通過命名管道相互通信的.NET應用程序。第一次通過時一切都很好,但在發送第一條消息並且服務器要再次收聽之後,WaitForConnection()方法會拋出System.IO.Exception,並顯示消息管道已損壞。
爲什麼我在這裏得到這個異常?這是我第一次使用管道工作,但是類似的模式在過去也適用於我的套接字。System.IO.Exception:管道中斷

代碼ahoy!
服務器:

using System.IO.Pipes; 

static void main() 
{ 
    var pipe = new NamedPipeServerStream("pipename", PipeDirection.In); 
    while (true) 
    { 
     pipe.Listen(); 
     string str = new StreamReader(pipe).ReadToEnd(); 
     Console.Write("{0}", str); 
    } 
} 

客戶:

public void sendDownPipe(string str) 
{ 
    using (var pipe = new NamedPipeClientStream(".", "pipename", PipeDirection.Out)) 
    { 
     using (var stream = new StreamWriter(pipe)) 
     { 
      stream.Write(str); 
     } 
    } 
} 

到sendDownPipe第一次調用獲取服務器打印我送就好了消息,但是當它循環回到再聽一遍,它poops。

+0

我認爲你有這個問題的原因是因爲該行的「新的StreamReader(管)」。創建的流讀取器的範圍是第一個while循環,然後重新創建。然而,流讀取器的行爲是關閉它們正在包裝的流 - 因此一旦它超出範圍,它將關閉管道流。你可以嘗試將它的聲明移出while循環並檢查(P.S:如果你這麼做的話,我沒有親自嘗試代碼的工作 - 只是想添加一個評論而不是回答) – user3141326 2016-04-07 15:05:43

回答

16

我會發布我的代碼,似乎工作 - 我很好奇,因爲我從來沒有做過任何與管道。我沒有在相關命名空間中找到您爲服務器端命名的類,因此這裏是基於NamedPipeServerStream的代碼。回調的東西只是因爲我不能被兩個項目困擾。

NamedPipeServerStream s = new NamedPipeServerStream("p", PipeDirection.In); 
Action<NamedPipeServerStream> a = callBack; 
a.BeginInvoke(s, ar => { }, null); 
... 
private void callBack(NamedPipeServerStream pipe) 
{ 
    while (true) 
    { 
    pipe.WaitForConnection(); 
    StreamReader sr = new StreamReader(pipe); 
    Console.WriteLine(sr.ReadToEnd()); 
    pipe.Disconnect(); 
    } 
} 

,客戶機將這樣的:

using (var pipe = new NamedPipeClientStream(".", "p", PipeDirection.Out)) 
using (var stream = new StreamWriter(pipe)) 
{ 
    pipe.Connect(); 
    stream.Write("Hello"); 
} 

我可以與服務器運行,沒有概率多次重複以上塊。

+0

這樣做。我猜想,當客戶脫離另一端時,他們不會有明顯的脫節。謝謝。 – 2009-05-22 14:06:03

5

當我從客戶端斷開連接後,從服務器調用pipe.WaitForConnection()時,發生了問題。該解決方案是再次趕上IOException異常和調用pipe.Disconnect(),然後調用pipe.WaitForConnection():

while (true) 
{ 
    try 
    { 
     _pipeServer.WaitForConnection(); 
     break; 
    } 
    catch (IOException) 
    { 
     _pipeServer.Disconnect(); 
     continue; 
    }    
}