I'm looking for a good sample where NamedPipeServerStream and NamedPipeServerClient can send messages to each other (when PipeDirection = PipeDirection.InOut for both). For now I found only this msdn article. But it describes only server. Does anybody know how client connecting to this server should look like?
1 Answer
What happens is the server sits waiting for a connection, when it has one it sends a string "Waiting" as a simple handshake, the client then reads this and tests it then sends back a string of "Test Message" (in my app it's actually the command line args).
Remember that the WaitForConnection
is blocking so you probably want to run that on a separate thread.
class NamedPipeExample
{
private void client() {
var pipeClient = new NamedPipeClientStream(".",
"testpipe", PipeDirection.InOut, PipeOptions.None);
if (pipeClient.IsConnected != true) { pipeClient.Connect(); }
StreamReader sr = new StreamReader(pipeClient);
StreamWriter sw = new StreamWriter(pipeClient);
string temp;
temp = sr.ReadLine();
if (temp == "Waiting") {
try {
sw.WriteLine("Test Message");
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}
}
Same Class, Server Method
private void server() {
var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);
StreamReader sr = new StreamReader(pipeServer);
StreamWriter sw = new StreamWriter(pipeServer);
do {
try {
pipeServer.WaitForConnection();
string test;
sw.WriteLine("Waiting");
sw.Flush();
pipeServer.WaitForPipeDrain();
test = sr.ReadLine();
Console.WriteLine(test);
}
catch (Exception ex) { throw ex; }
finally {
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
}
} while (true);
}
}
-
2Thank you! You helped me to realize what was the problem with my code. I was leaving server waiting to read something from client (in separate thread), and in the same time was trying to send a message to client. The code was hanging on sw.WriteLine. It seems that it is not possible for server to wait for message and send one in the same time.– NatFeb 3, 2012 at 9:12
-