16.5. Using Named Pipes to Communicate
Problem
You need a way to use named pipes to communicate with another application across the network.
Solution
Use the new NamedPipeClientStream
and NamedPipeServerStream
in the System.IO.Pipes
namespace. You can then create a client and server to work with named pipes.
In order to use the NamedPipeClientStream
class, you need some code like that shown in Example 16-3.
Example 16-3. Using the NamedPipeClientStream class
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; using System.IO.Pipes; namespace NamedPipes { class NamedPipeClientConsole { static void Main( ) { // set up a message to send string messageText = "This is my message!"; int bytesRead; // set up the named pipe client and close it when complete using (NamedPipeClientStream clientPipe = new NamedPipeClientStream(".","mypipe", PipeDirection.InOut,PipeOptions.None)) { // connect to the server stream clientPipe.Connect( ); // set the read mode to message clientPipe.ReadMode = PipeTransmissionMode.Message; // write the message ten times for (int i = 0; i < 10; i++) { Console.WriteLine("Sending message: " + messageText); byte[] messageBytes = Encoding.Unicode.GetBytes(messageText); // check and write the message if (clientPipe.CanWrite) { clientPipe.Write(messageBytes, 0, messageBytes.Length); clientPipe.Flush( ); // wait till it is read clientPipe.WaitForPipeDrain( ); } // set up a buffer for the message bytes messageBytes = new ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.