5

I'm trying to use NamedPipeServerStream to create a named pipe server in .Net 4. I'm using BeginWaitForConnection to wait for the connection, so that I can abort the wait if the server is to be shut down.

Everything works well for the first client --- the connection is acknowledged, the data received, and the response sent OK. However, after the client disconnects everything breaks. I'm calling BeginWaitForConnection again to wait for a new connection, but this is throwing an IOException saying that the "pipe is broken".

How can I wait for a second client on the same pipe?

Lu4
  • 14,873
  • 15
  • 79
  • 132
Anthony Williams
  • 66,628
  • 14
  • 133
  • 155

2 Answers2

5

Create a new instance of NamedPipeServerStream specifying the same pipe, and call BeginWaitForConnection on that.

i.e. Don't try to reuse a NamedPipeServerStream object for different clients: one instance should service one client connection/conversation, then be disposed.

See also Multithreaded NamePipeServer in C#

Community
  • 1
  • 1
Chris Dickson
  • 11,964
  • 1
  • 39
  • 60
0

Another method when using a single client/server configuration is to Disconnect the pipe stream when the client disconnects to clean up the pipe. This allows reuse of the pipe. When you call BeginWaitForConnection again, it will begin accepting connections.

while (true) 
{
    pipe.BeginWaitForConnection();
    // read and write to pipe
    // catch exception when client disconnects
    pipe.Disconnect();
}
Gerard Sexton
  • 3,114
  • 27
  • 36
  • You also have to be careful about not disposing/closing stream readers/writers that you're using with the named pipe stream as they will close the underlying stream and then it cannot be reused. – Charles A. Dec 10 '20 at 01:28