I tried to find a good and clear example of an asynchronous NamedPipeServerStream and could not find a suitable one for me.
I want to have a NamedPipe server that asynchronously receives messages from clients. The client is simple and suitable for me. But I cannot find server examples or cannot understand how this works.
Now, as I understand it, I need to create a NamedPipeServerStream object. Let me do this:
namedPipeServerStream = new NamedPipeServerStream(PIPENAME, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, BUFFERSIZE, BUFFERSIZE);
It seems to need work. But I don’t know, do I need to use PipeSecurity or PipeAccessRule at all? I AM? My server will run as a Windows service on the local system.
What's next? I think I need to use BeginWaitForConnection for asynchronous connections. Let's get a look:
namedPipeServerStream.BeginWaitForConnection(WaitForConnectionAsyncCallback, <some strange thing>);
Question 1 : What is this “weird thing”? How to use it?
Question 2 : should I do
while(true) { namedPipeServerStream.BeginWaitForConnection(WaitForConnectionAsyncCallback, <some strange thing>); }
So that my server always waits for connections? Or do I need to do it somehow else?
And then ... Let me take a look at the 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, of course, does not work. Since , I do not know how to get the string from the stream exactly. How? Now it throws an InvalidOperationException:
The pipe is not yet connected.
So how to organize asynchronous work with NamedPipeServerStream?