Original: instance of process communication using named pipes in C #
1 New Solution namedpipeexample
Create a new two project under the solution:Client and Server, both with the output type ofWindows application. The structure of the entire program is as shown.
2 implementing the project Client
The client contains only one form named "Clients," as shown in.
Write the form back-end code as shown below.
Using system;using system.io;using system.io.pipes;using system.security.principal;using System.Windows.Forms; namespace client{public partial class Frmclient:form {Namedpipeclientstream pipeclient = new N Amedpipeclientstream ("localhost", "testpipe", Pipedirection.inout, Pipeoptions.asynchronous, Tokenimpersonationlevel.none); StreamWriter SW = null; Public Frmclient () {InitializeComponent (); private void Frmclient_load (object sender, EventArgs e) {try {pipe Client.connect (5000); SW = new StreamWriter (pipeclient); Sw. AutoFlush = true; } catch (Exception ex) {MessageBox.Show ("Connection setup failed, make sure the server-side program has been opened. "); This. Close (); }} private void Btnsend_click (object sender, EventArgs e) {if (SW! = null) { Sw. WriteLine(This.txtMessage.Text); } else {MessageBox.Show ("The connection is not established and the message cannot be sent. "); } } }}
3 Implementing Project Server
The Server project contains only a form named "Server Side", as shown in.
Write the form back-end code as shown below.
Using system;using system.io;using system.io.pipes;using system.threading;using System.Windows.Forms; namespace server{public partial class Frmserver:form {Namedpipeserverstream pipeserver = new N Amedpipeserverstream ("Testpipe", pipedirection.inout,1,pipetransmissionmode.message,pipeoptions.asynchronous); Public Frmserver () {InitializeComponent (); } private void Frmserver_load (object sender, EventArgs e) {ThreadPool.QueueUserWorkItem (Delegat e {pipeserver.beginwaitforconnection ((o) = = {Namedpipese Rverstream pserver = (namedpipeserverstream) o.asyncstate; Pserver.endwaitforconnection (o); StreamReader sr = new StreamReader (pserver); while (true) {this. Invoke ((MethodInvoker) Delegate {lsvMessage.Items.Add (Sr. ReadLine ()); }); }}, Pipeserver); }); } }}
4 Running the program
Run the Server.exe with the Client.exe program, as shown in the effect.
The instance sends a total of three messages, each of which transmits data in three.
The client and server-side programs shown in this example are located on the local machine and use named Pipes to communicate with other processes on the network.
Instances of process communication using named pipes in C #