Use the Named Pipe in. NET to complete inter-process communication from the Network)

Source: Internet
Author: User
Tags readfile

Have you ever had to exchange data between two. NET applications on the same machine? For example, a Web site and a Windows service ?. NET Framework provides several good options to complete inter-process communication (IPC): Web Service, Remoting. The fastest is Remoting, because it uses the TCP channel and binary format.

However, if you need to call another application from one application frequently, and you are mainly concerned about performance, Remoting is still a little slower. What slows down Remoting is not a protocol, but serialization.

In general, Remoting is good, but if only two processes on the local machine communicate with each other, its processing mechanism increases unnecessary overhead. Therefore, we need to consider some other options. The better is the Named pipeline (Named Pipes), which does not perform binary serialization, So it provides a faster IPC.

Remember, the most effective use of this solution is when one application needs to communicate with another application frequently and in short text, it is on the same machine or within the same LAN. For structured data exchange, these text messages can also be XML documents or serialized. NET objects. There is no security layer during communication, because the named pipe can only run in the LAN at most, so it is assumed that security issues are handled by other layers.

1. Implement named Pipelines

The following are the main classes in the. NET naming pipeline solution.

  • NamedPipeNative: this class is associated with kernal32.dll to implement communication between named pipelines, including some common methods and constants.
  • NamedPipeWrapper: this class is a package of NamedPipeNative.
  • ApipeConnection: This is an abstract class that defines the methods for naming pipe connections, reading, and writing data. This class is inherited from ClientPipeConnection and ServerPipeConnection, which are used in client and server applications respectively.
  • ClientPipeConnection: used by client applications to communicate with servers using named pipes.
  • ServerPipeConnection: allows the named pipe server to create a connection and communicate with the client.
  • PipeHandle: stores the local handle of the operating system and the current status of the Pipeline Connection.

After learning about the above classes, you need to understand the operation of the named pipeline.

2. Create a server named pipe

The syntax of the server-side MPs queue name is \. \ pipe \ PipeName. The "PipeName"... section is the specific name of the pipeline. To connect to the MPs queue, a client named MPs queue with the same name must be created for the client application. If the client is on a different machine, the name of the SERVER-side pipeline should be \ SERVER \ pipe \ PipeName. The following code is a static method of NamedPipeWrapper. It is used to instantiate a server-side named pipe.

Public static PipeHandle Create (string name, uintoutBuffer, uintinBuffer ){
Name = @ "\. \ pipe \" + name;
PipeHandle handle = new PipeHandle ();

For (inti = 1; I <= ATTEMPTS; I ++ ){
Handle. State = InterProcessConnectionState. Creating;
Handle. Handle = NamedPipeNative. CreateNamedPipe (name,
NamedPipeNative. PIPE_TYPE_MESSAGE |
NamedPipeNative. PIPE_WAIT,
IntPtr. Zero );
If (handle. Handle. ToInt32 ()! = NamedPipeNative. INVALID_HANDLE_VALUE ){
Handle. State = InterProcessConnectionState. Created;

If (I> = ATTEMPTS ){
Handle. State = InterProcessConnectionState. Error;
Throw new NamedPipeIOException ("Error creating named
Pipe "+ name +". Internalerror: "+ NamedPipeNative. GetLastError (). ToString (), NamedPipeNative. GetLastError ());

By calling the NamedPipeNative. CreateNamedPipe method, the above method creates a named pipeline for mutual communication, and the specified pipeline can have unlimited instances. The constant names are all in English. It is not difficult to understand them.

Assuming that the named pipe on the server side is successfully created, it can start listening to the client connection.

3. Connect to the client Pipeline

The named MPs Queue Server must be set to the listening status so that the client MPs queue can connect to it. This can be done by calling the NamedPipeNative. ConnectNamedPipe method.

Call the NamedPipeNative. CreateFile method to create a named pipeline client and connect it to the server pipeline of a listener. The following code is part of NamedPipeWrapper. ConnectToPipe.

Public static PipeHandle ConnectToPipe (string pipeName, string serverName ){
PipeHandle handle = new PipeHandle ();
// Buildthename ofthe pipe.
String name = @ "\" + serverName + @ "\ pipe \" + pipeName;
For (inti = 1; I <= ATTEMPTS; I ++ ){
Handle. State = InterProcessConnectionState. ConnectingToServer;
// Try to connect to the server
Handle. Handle = NamedPipeNative. CreateFile (name, NamedPipeNative. GENERIC_READ | NamedPipeNative.
GENERIC_WRITE, 0, null, NamedPipeNative. OPEN_EXISTING, 0, 0 );

After creating a PipeHandle object and creating a pipeline name, we call NamedPipeNative. CreateFile to create a client named pipeline and connect it to the specified server-side pipeline. In our example, the client pipeline is configured as readable and writable.

If the client pipeline is successfully created, the NamedPipeNative. CreateFile method returns the corresponding local handle, which will be used in future operations. If creation fails for some reason, the method returns 1 and sets NamedPipeNative as the INVALID_HANDLE_VALUE constant.

Before the client naming pipeline can be used for reading and writing, you need to do one more thing. We need to set handle to PIPE_READMODE_MESSAGE. You can call NamedPipeNative. SetNamed-PipeHandleState.

If (handle. Handle. ToInt32 ()! = NamedPipeNative. INVALID_HANDLE_VALUE ){
// The client managed to connect to the server pipe
Handle. State = InterProcessConnectionState.

// Set the read mode of the pipe channel
Uint mode = NamedPipeNative. PIPE_READMODE_MESSAGE;

If (NamedPipeNative. SetNamedPipeHandleState (handle. Handle, refmode, IntPtr. Zero, IntPtr. Zero )){

Each client pipeline communicates with an instance of a server pipeline. If the maximum number of server-side instances is reached, the creation of the client pipeline will fail.

4. Read and Write Data

When reading data from a named pipeline, we cannot know the message length in advance. Our solution does not need to process long messages, so the System. Int32 variable is used to specify the message length.

The NamedPipeWrapper. WriteBytes method can write messages to a named pipe. messages are UTF-8 encoded and then transmitted in byte arrays.

Public static void WriteBytes (PipeHandle handle, byte [] bytes ){
Byte [] numReadWritten = new byte [4];
Uint len;

If (bytes = null ){
Bytes = newbyte [0];
If (bytes. Length = 0 ){
Bytes = new byte [1];
Bytes = System. Text. Encoding. UTF8.GetBytes ("");
// Obtain the message length:
Len = (uint) bytes. Length;

Handle. State = InterProcessConnectionState. Writing;
// Get the message Length Byte representation. Write the four bytes first.
If (NamedPipeNative. WriteFile (handle. Handle, BitConverter. GetBytes (len), 4, numReadWritten, 0 )){
// Write the remaining message
If (! NamedPipeNative. WriteFile (handle. Handle, bytes, len, numReadWritten, 0 )){
Handle. State = InterProcessConnectionState. Error;
ThrownewNamedPipeIOException ("Errorwritingtopipe. Internalerror:" + NamedPipeNative. GetLastError (). ToString (), NamedPipeNative. GetLastError ());
Else {
Handle. State = InterProcessConnectionState. Error;
ThrownewNamedPipeIOException ("Errorwritingtopipe. Internalerror:" + NamedPipeNative. GetLastError (). ToString (),
NamedPipeNative. GetLastError ());

Handle. State = InterProcessConnectionState. Flushing;
// Activate the MPs queue to ensure that any cached data is written to the MPs queue and will not be lost:
Flush (handle );
Handle. State = InterProcessConnectionState. FlushedData;

To read data from a named pipeline, first convert the first four bytes into Integers to determine the message length. Next, you can read the remaining data. Please refer to the NamedPipeWrapper. ReadBytes method below.

Public static byte [] ReadBytes (PipeHandle handle, int maxBytes ){
Byte [] numReadWritten = newbyte [4];
Byte [] intBytes = newbyte [4];
Byte [] msgBytes = null;

Handle. State = InterProcessConnectionState. Reading;
Handle. State = InterProcessConnectionState. Flushing;
// Read the first four bytes and convert them into integers:
If (NamedPipeNative. ReadFile (handle. Handle, intBytes, 4, numReadWritten, 0 )){
Len = BitConverter. ToInt32 (intBytes, 0 );
MsgBytes = newbyte [len];
Handle. State = InterProcessConnectionState. Flushing;
// Read the remaining data or throw an exception:
If (! NamedPipeNative. ReadFile (handle. Handle, msgBytes, (uint) len, numReadWritten, 0 )){
Handle. State = InterProcessConnectionState. Error;
ThrownewNamedPipeIOException ("Error readingfrompipe. Internalerror:" + NamedPipeNative. GetLastError (). ToString (), NamedPipeNative. GetLastError ());
Else {
Handle. State = InterProcessConnectionState. Error;
ThrownewNamedPipeIOException ("Errorreadingfrompipe. Internalerror:" + NamedPipeNative. GetLastError (). ToString (), NamedPipeNative. GetLastError ());
Handle. State = InterProcessConnectionState. ReadData;
If (len> maxBytes ){
Returnnull ;}

The above is the implementation of the named pipeline and some main methods. The following describes how to create a named pipeline server and client application for text message communication.

5. Create a named pipeline Server

The named MPs Queue Server is a multithreaded engine used to create new threads and MPs queue connections for concurrent request services.

AppModule. NamedPipes assembly contains a base class ApipeConnection, which encapsulates operations on common named pipelines, such as creating pipelines and reading and writing data. This is an abstract class.

In addition, there are two Pipeline Connection classes inherited from ApipeConnection: ClientPipeConnection and ServerPipeConnection. They reload some methods (such as connection and close) and provide implementation for the server and client named pipe respectively. Both ClientPipeConnection and ServerPipeConnection have the Destructor that calls the Dispose method,
Clear uncontrolled resources.

The named MPs Queue Server is responsible for creating named MPs queues and processing client connections. Two main classes provide service functions: ServerNamedPipe and PipeManager.

(1) ServerNamedPipe class

The constructor is as follows :..

Internal ServerNamedPipe (stringname, uint outBuffer, uintinBuffer, intmaxReadBytes ){
PipeConnection = newServerPipeConnection (name, outBuffer, inBuffer, maxReadBytes );
PipeThread = newThread (newThreadStart (PipeListener ));
PipeThread. IsBackground = true;

PipeThread. Name = "PipeThread" + this. PipeConnection. NativeHandle. ToString ();
LastAction = DateTime. Now;

The constructor creates a new ServerPipeConnection instance and calls the PipeListener method. The subsequent main parts are loop listening to client connections and reading and writing data.

Private void PipeListener (){
CheckIfDisposed ();

Try {
Listen = Form1.PipeManager. Listen;
Form1.ActivityRef. AppendText ("Pipe" + this. PipeConnection. NativeHandle. ToString () + ": new pipe started" + Environment. NewLine );
While (Listen ){
LastAction = DateTime. Now;
// Read data from the client pipeline:
Stringrequest = PipeConnection. Read ();
LastAction = DateTime. Now;
If (request. Trim ()! = ""){
// The PipeManager. HandleRequest method accepts client requests for processing,
// Then respond, and the response is then written to the pipeline.
PipeConnection. Write (Form1.PipeManager. HandleRequest (request ));
Form1.ActivityRef. AppendText ("Pipe" + this. PipeConnection. NativeHandle. ToString () + ": requesthandled" + Environment. NewLine );
Else {PipeConnection. Write ("Error: badrequest ");}
LastAction = DateTime. Now;
// Disconnect from the client Pipe
PipeConnection. Disconnect ();
If (Listen ){
Form1.ActivityRef. AppendText ("Pipe" + this. PipeConnection. NativeHandle. ToString () + ": listening" + Environment. NewLine );

// Start listening for a new connection:

Connect ();}
Form1.PipeManager. WakeUp ();
Catch (System. Threading. ThreadAbortExceptionex ){}
Catch (System. Threading. ThreadStateExceptionex ){}
Catch (Exceptionex ){
// Logexception
Finally {
This. Close ();}

Do not close the server pipeline because creating a server pipeline is a relatively expensive operation, which may cause expensive overhead.

(2) PipeManager class

The PipeManager class is responsible for creating server pipelines, managing threads, and generating responses to client requests when necessary. In the following code, the Initialize method calls the Start method to create a new thread:

Public void Initialize (){
Pipes = Hashtable. Synchronized (_ pipes );

Mre = newManualResetEvent (false );
MainThread = newThread (newThreadStart (Start ));
MainThread. IsBackground = true;
MainThread. Name = "MainPipeThread ";

MainThread. Start ();
Thread. Sleep (1000 );

The PipeManager class only creates new pipeline connections and threads when receiving requests. This means that the ServerPipeConnection object is created only when no connection exists or all connections are busy responding to requests. Generally, two or three named MPs queue instances can process high-load concurrent client requests, but this mainly depends on the processing of client requests and
The response time.

The reference of the created ServerPipeConnection object is saved in the pipeline hash table.

Private void Start (){
Try {

While (_ listen ){
Int [] keys = newint [Pipes. Keys. Count];
Pipes. Keys. CopyTo (keys, 0 );

// Cyclically check whether the ServerPipeConnection object is still available:
Foreach (intkeyinkeys ){
ServerNamedPipeserverPipe = (ServerNamedPipe) Pipes [key];
If (serverPipe! = Null & DateTime. Now. Subtract (serverPipe. LastAction). Milliseconds>
PIPE_MAX_STUFFED_TIME & serverPipe. PipeConnection. GetState ()! = InterProcessConnectionState. WaitingForClient ){
ServerPipe. Listen = false;
ServerPipe. PipeThread. Abort ();
RemoveServerChannel (serverPipe. PipeConnection. NativeHandle );
// The NumberPipes field contains the maximum number of named pipelines that can be owned on the server.
If (numChannels <= NumberPipes ){
ServerNamedPipe pipe = new ServerNamedPipe (PipeName, OutBuffer, InBuffer, MAX_READ_BYTES );
Try {
// The Connect method sets the newly generated pipeline to the listening mode.
Pipe. Connect ();
Pipe. LastAction = DateTime. Now;
System. Threading. Interlocked. Increment (refnumChannels );
// Start the ServerPipeConnection thread
Pipe. Start ();
Pipes. Add (pipe. PipeConnection. NativeHandle, pipe );
Catch (InterProcessIOException ex ){
RemoveServerChannel (pipe. PipeConnection. NativeHandle );
Pipe. Dispose ();
Else {Mre. Reset (); Mre. WaitOne (1000, false );}
Catch {// Logexception}

6. Create a client pipe connection

To connect a client application to the server using a named pipeline, we must create an instance of the ClientPipeConnection class and use it to read and write data.

IInterProcessConnectionclientConnection = null;

Try {
ClientConnection = newClientPipeConnection ("MyPipe ",".");
ClientConnection. Connect ();
ClientConnection. Write (textBox1.Text );
ClientConnection. Close ();
Catch {
ClientConnection. Dispose ();

The pipe name "MyPipe" must be the same as the name of the server pipe. if the name of the pipe server is also on the same machine, the second parameter of the ClientPipeConnection constructor should be ".". If not on the same machine, the second parameter is the Network Name of the server.

As mentioned above, I have introduced the solution of the named pipeline. I reiterate that the most effective use of the named pipeline is that one application needs to be frequently used with another application, in the case of short text message communication, and on the same machine or within the LAN. If you encounter such a situation, I hope these codes can give you inspiration and reference.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.