Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Named Pipes, how to detect a client disconnecting

My current named pipe implementation reads like this:

while (true)
{
  byte[] data = new byte[256];                        
  int amount = pipe.Read(data, 0, data.Length);
  if (amount <= 0)
  {
      // i was expecting it to go here when a client disconnects but it doesnt
     break;
  }
  // do relevant stuff with the data
}

how can I correctly detect when a client disconnects?

like image 638
clamp Avatar asked Oct 03 '22 23:10

clamp


2 Answers

Set a read timeout and poll the NamedPipeClientStream.IsConnected flag when a timeout occurs.

A Read Timeout will cause reads that are idle for the timeout duration to throw InvalidOperationException

If you are not reading, and want to detect disconnections, call this method on a worker thread for the lifetime of your pipe connection.

while(pipe.IsConnected && !isPipeStopped) //use a flag so that you can manually stop this thread
{
    System.Threading.Thread.Current.Sleep(500);
}

if(!pipe.IsConnected)
{
    //pipe disconnected
    NotifyOfDisconnect();
}
like image 183
Gusdor Avatar answered Oct 10 '22 01:10

Gusdor


One easy way to tell if your pipe has been broken (remotely) is to always use asynchronous reads instead of sync ones, and to always have at least one read submitted asynchronously. That is, for every successful read you get, post another async read, whether you intend to read another or not. If you close the pipe, or the remote end closes it, you'll see the async read complete, but with a null read size. You can use this to detect a pipe disconnection. Unfortunately, the pipe will still show IsConnected, and you still need to manually close it, I think, but it does allow you to detect when something went wonky.

like image 28
eric frazer Avatar answered Oct 10 '22 03:10

eric frazer