C # Namepipe Usage Summary

Source: Internet
Author: User

I recently used a named pipe in C # in a project, so write a summary memo here.

Why use Named pipes? In order to achieve data exchange between the two programs. Assume the following scenario. On the same PC, program A and program B need data communication, and we can use named pipe technology to implement it. The two objects of the named pipe. Namedpipeclientstream and Namedpipeserverstream objects. The party requesting the communication is the client side, and the party sending the data is the server side.

Use Namedpipe to communicate if the server side crashes and does not affect the client.

Here's an example to illustrate:

Server side:

Ui:

    <Grid><Grid.rowdefinitions><RowDefinitionHeight="*"/><RowDefinitionHeight= "Auto"/><RowDefinitionHeight= "Auto"/><RowDefinitionHeight="*"/></Grid.rowdefinitions><Grid.columndefinitions><ColumnDefinitionWidth= "Auto"/><ColumnDefinitionWidth="*"/></Grid.columndefinitions><TextBlockText= "Received Message:"Grid.Row= "1"Margin= "10"/><TextBlockx:name= "Tblrecmsg"VerticalAlignment= "Center"Grid.Row= "1"Grid.column= "1"/><ButtonContent= "Send"Grid.Row= "2" Margin= "Ten" click= "OnSend"/> <TextBox x:name= "Txtsendmsg"  VerticalAlignment= "Center" grid.row= "2" grid.column= "1" Margin= "Ten"/> </Grid>                

Code:

PrivateNamedpipeserverstream _pipe;PrivateConstString pipename ="Pipesample";PrivateConstint pipeinbuffersize =4096;PrivateConstint pipeoutbuffersize =65535;Private Encoding Encoding =Encoding.UTF8;PublicMainWindow () {InitializeComponent (); _pipe =NewNamedpipeserverstream (Pipename, Pipedirection.inout,1, Pipetransmissionmode.message, Pipeoptions.asynchronous |Pipeoptions.writethrough, Pipeinbuffersize, pipeoutbuffersize); _pipe. Beginwaitforconnection (Waitforconnectioncallback, _pipe); }PrivatevoidWaitforconnectioncallback (IAsyncResult ar) {var pipeserver =(Namedpipeserverstream) AR. asyncstate; Pipeserver.endwaitforconnection (AR);var data =NewByte[Pipeinbuffersize];var count = pipeserver.read (data,0, pipeinbuffersize);if (Count >0) {//The communication parties can agree the form of the transmission content, in the example we transmit simple text information.String message = Encoding. GetString (data,0, count); Dispatcher.begininvoke (New Action (() ={tblrecmsg.text = message;})); }} private void OnSend (object sender, RoutedEventArgs e) { if (_pipe. isconnected) { try { string message = Txtsendmsg.text; byte[] data = encoding. GetBytes (message); _pipe. Write (data, 0, data. Length); _pipe. Flush (); _pipe. Waitforpipedrain (); } catch {}} Close ();}               

Client side:

Ui:

    <Grid><Grid.rowdefinitions><RowDefinitionHeight="*"/><RowDefinitionHeight= "Auto"/><RowDefinitionHeight= "Auto"/><RowDefinitionHeight="*"/></Grid.rowdefinitions><Grid.columndefinitions><ColumnDefinitionWidth= "Auto"/><ColumnDefinitionWidth="*"/></Grid.columndefinitions><ButtonContent= "Connect"Margin= "10"Click= "OnConnect"/> <TextBlock Text= "Received Message:" grid.row= "1" Margin= "Ten"/> <TextBlock x:name= "tblrecmsg" grid.row= "1" grid.column= "1"/> </Grid>                

Code:

PrivateConstString pipeservername ="PipeServer.exe";PrivateConstString pipename ="Pipesample";Private Encoding Encoding =Encoding.UTF8;PrivateNamedpipeclientstream _pipe;PrivateBOOL _starting =False;PublicMainWindow () {InitializeComponent ();}Privatevoid OnConnect (Objectsender, RoutedEventArgs e) {If(_starting) {Return; }var path =System.IO.Path.Combine (System.AppDomain.CurrentDomain.BaseDirectory, pipeservername);var startinfo =NewProcessStartInfo (path) {UseShellExecute =False, CreateNoWindow =True};Try{var process =Process.Start (StartInfo); _pipe =NewNamedpipeclientstream (".", Pipename, pipedirection.inout, pipeoptions.asynchronous |Pipeoptions.writethrough); _pipe. Connect (); _pipe. ReadMode =Pipetransmissionmode.message;String message ="connected!";byte[] data =Encoding. GetBytes (message); _pipe. BeginWrite (data,0, data. Length, Pipewritecallback, _pipe); _starting =True; }Catch(Exception ex) {Debug.Write (ex. StackTrace); } }PrivatevoidPipewritecallback (IAsyncResult ar) {var pipe = (Namedpipeclientstream) ar. asyncstate; Pipe. EndWrite (AR); Pipe. Flush (); Pipe. Waitforpipedrain (); var data = new byte[< Span style= "color: #800080;" >65535var count = pipe. Read (data, 0if (Count > 0string message = Encoding. GetString (data, 0new Action (() => message;}); } } 

Note: Because we are communicating on the same PC, we just need to set pipeserver in the Namedpipeclientstream construction parameter to "." Can. Also, because this is just an example, only the simple string type is passed in Pipeserver. Of course, other types of content can also be passed.

Operating effect:

Thank you for reading!

C # Namepipe Usage Summary

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: info-contact@alibabacloud.com 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.