Letting processes communicate on Windows can be done on several ways. By sending Windows messages, opening network connections via sockets or via Named Pipes. Here a minimalistic example of a Named Pipe Client and also its counter part, the server.
With this example code only one client can connect to the server. If you want to connect with multiple clients at the same time you either use a multithreaded Named Pipe server or you set the Named Pipes parthat way they can handle all the clients at the same time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | using System; using System.IO; using System.IO.Pipes; using System.Collections.Generic; using System.Windows.Forms; namespace PipeClient { class PipeClient { /* * Starting the Named Pipe Server part * */ private static void StartServer(String pPipeName) { string lTemp = String.Empty; using (NamedPipeServerStream pPipeServer = new NamedPipeServerStream(pPipeName, PipeDirection.InOut)) { // Wait for a client to connect Console.Write("Waiting for client connection..."); pPipeServer.WaitForConnection(); Console.WriteLine("Client connected."); try { using (StreamReader lStrReader = new StreamReader(pPipeServer)) { while ((lTemp = lStrReader.ReadLine()) != null) { Console.WriteLine("Received data from server: {0}", lTemp); } // while ((lT... } // using (StreamR... } catch (Exception lEx) { Console.WriteLine("Exception catched : {0}", lEx.Message); } } // using (Name... } /* * Starting the Named Pipe Client part * */ private static void StartClient(String pPipeName) { using (NamedPipeClientStream pPipeClient = new NamedPipeClientStream(".", pPipeName, PipeDirection.Out)) { pPipeClient.Connect(); Console.WriteLine("Connected to pipe."); using (StreamWriter lStrWriter = new StreamWriter(pPipeClient)) { lStrWriter.AutoFlush = true; Console.Write("Enter text : "); lStrWriter.WriteLine(Console.ReadLine()); } // using (S... } // using (NamedPip... } /* * * */ static void Main(string[] pArgs) { Console.Clear(); if (pArgs.Length != 2 || !(pArgs[0] == "-c" || pArgs[0] == "-s")) { Console.WriteLine("Usage: {0} -c|-s PipeName\n", Application.ProductName); Application.Exit(); } // if (args... if (pArgs[0] == "-c") StartClient(pArgs[1]); else if (pArgs[0] == "-s") StartServer(pArgs[1]); } } } |