Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
881 views
in Technique[技术] by (71.8m points)

c# - System.IO.Exception: Pipe is broken

I have two .NET applications that talk to each other over a named pipe. Everything is great the first time through, but after the first message is sent, and the server is going to listen again, the WaitForConnection() method throws a System.IO.Exception with message Pipe is broken.
Why am I getting this exception here? This is my first time working with pipes, but a similar pattern has worked for me in the past with sockets.

Code ahoy!
Server:

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);
    }
}

Client:

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

The first call to sendDownPipe gets the server to print the message I send just fine, but when it loops back up to listen again, it poops.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll post my code that seems to work - I was curious since I never did anything with pipes. I didn't find the class you name for the server-side in the relevant namespace, so here's the code based on the NamedPipeServerStream. The callback stuff is just because I couldn't be bothered with two projects.

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();
  }
}

And the client does this:

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

I can repeat above block multiple times with the server running, no prob.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...