I was trying to find any good and clear example of asynchronous NamedPipeServerStream and couldn't find any suitable for me.
I want to have NamedPipe Server which is asynchronously accept messages from clients. The client is simple and it's fine for me. But I can't find examples of server, or can't understand how it works.
Now as I understand I need to create NamedPipeServerStream object. Let's do this:
namedPipeServerStream = new NamedPipeServerStream(PIPENAME, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, BUFFERSIZE, BUFFERSIZE);
Seems to work. But I don't know, do I have to use PipeSecurity or PipeAccessRule at all? Do I? My server will work as a windows service in a local system.
What next? I'm thinking I need to use BeginWaitForConnection for async connections. Let's see:
namedPipeServerStream.BeginWaitForConnection(WaitForConnectionAsyncCallback, <some strange thing>);
Question 1: What is this "some strange thing"? How to use it?
Question 2: Should I do
while(true)
{
namedPipeServerStream.BeginWaitForConnection(WaitForConnectionAsyncCallback, <some strange thing>);
}
To make my server always wait for connections? Or I need to do it somehow else?
And then... Let's take a look into WaitForConnectionAsyncCallback function:
private void WaitForConnectionAsyncCallback(IAsyncResult result)
{
Console.WriteLine("Client connected.");
byte[] buff = new byte[BUFFERSIZE];
namedPipeServerStream.Read(buff, 0, namedPipeServerStream.InBufferSize);
string recStr = General.Iso88591Encoding.GetString(buff, 0, namedPipeServerStream.InBufferSize);
Console.WriteLine(" " + recStr);
namedPipeServerStream.EndWaitForConnection(result);
}
..This doesn't work of course. Because I don't know how exactly to receive string from stream. How? Now it raises an InvalidOperationException:
Pipe hasn't been connected yet.
So how to organize asynchronous work with NamedPipeServerStream?