目录结构:

contents structure [+]

管道为进程间通信提供了一种可能。管道分为两种,一种是匿名管道,另一种是命名管道。

1.匿名管道(anonymous pipe)

匿名管道,匿名管道只提供在本地电脑进程间的通信。匿名管道比命名管道花费的开销更少,但提供的服务也比命名管道的少。匿名管道是单向的,而且不能用于网络通信。匿名管道只支持单服务器实例。

匿名管道不支持消息传输模式(PipeTransmissionMode.Message),仅支持字节传输模式(PipeTransmissionMode.Byte)。

创建匿名管道需要使用AnonymousPipeClientStream和AnonymousPipeServerStream类,下面的案例展示了匿名的管道的用法。
首先创建一个PipeServer.cs文件,其内容如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace PipeServer
{
class Program
{
static void Main(string[] args)
{
Process pipeClient1=new Process();
pipeClient1.StartInfo.FileName = @"PipeClient.exe"; //AnonymousPipeServerStream is an one-way pipe. in other words it's only support PipeDirection.In or PipeDirection.Out.
//in this program, we use PipeDirection.Out for send data to clients.
using (AnonymousPipeServerStream pipeServer =
new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) { //send the client handle that from AnonymousPipeServerStream to client
pipeClient1.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
pipeClient1.StartInfo.UseShellExecute = false;
pipeClient1.Start(); //closes the local copy of the AnonymousPipeClientStream object's handle
//this method must be call after the client handle has been passed to the client
//if this method isn't called, then the AnonymousPipeServerStream will not receive notice when client dispose of it's PipeStream object
pipeServer.DisposeLocalCopyOfClientHandle(); try
{
using(StreamWriter sw=new StreamWriter(pipeServer)){
//automatic flush
sw.AutoFlush = true; sw.WriteLine("SYNC");
//it'll block util the other end of pipe has been read all send bytes
pipeServer.WaitForPipeDrain(); String temp=null;
while(true){
temp=Console.ReadLine();
//send message to pipeclient from console
sw.WriteLine(temp);
//it'll block util the other end of pipe has been read all send bytes
pipeServer.WaitForPipeDrain();
if(temp=="exit"){
break;
}
}
}
}
catch (IOException e) {
Console.WriteLine("[server] exception:{0}",e.Message);
}
} pipeClient1.WaitForExit();
pipeClient1.Close(); }
}
}

PipeServer.cs

然后创建PipeClient.cs文件,内容如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks; class Program
{
static void Main(string[] args)
{ using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, args[])) { using (StreamReader sr = new StreamReader(pipeClient)) {
String temp = null;
Console.WriteLine("[client] wait for sync ...");
do{
temp = sr.ReadLine();
}while(!temp.StartsWith("SYNC"));
Console.WriteLine("client in");
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("[client] receive message: " + temp);
if(temp=="exit"){
break;
}
}
}
Console.Write("[client] Press Enter to exist...");
Console.ReadLine();
}
}
}

PipeClient.cs

这里只展示一个服务端一个客户端,但实际中可以有多个客户端。PipeClient.cs和PipeServer.cs应该在同一个文件夹下面,具体的路径由PipeServer.cs中加载客户端的路径决定,本例中是在同一路径下。然后可以使用csc将其都编译为可执行文件。

2.命名管道(named pipe)

命名管道和匿名管道的功能相似,但他们有如下两点区别:

  • 命名管道既可以支持直接传输模式(PipeTransmissionMode.Byte),也可以支持消息传输模式(PipeTransmissionMode.Message)
  • 命名管道既可以用于本地进程间的通信,也可以用于网络通信。

创建命名管道需要使用NamedPipeServerStream和NamedPipeClientStream类,下面的案例展示了命名管道的用法:
PipeServer.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace PipeServer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Waiting client to connect...\n"); using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut))
{ //wait client to connect
pipeServer.WaitForConnection(); Console.WriteLine("[server] a client connected"); StreamReader reader = new StreamReader(pipeServer);
StreamWriter writer = new StreamWriter(pipeServer);
writer.AutoFlush = true; String line = null;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine("[server] receive message:"+line); writer.WriteLine("I'm fine"); pipeServer.WaitForPipeDrain(); if ("line" == "EXIT")
{
break;
}
}
}; Console.ReadLine();
}
}
}

PipeServer.cs

PipeClient.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace PipeClient
{
class Program
{
static void Main(string[] args)
{
//initialize NamePipeClientStream with serverName,pipeName,pipeDirection
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream("host path", "testpipe", PipeDirection.InOut)) { Console.WriteLine("[client] Attemping to connect to pipe...");
pipeClient.Connect(); Console.WriteLine("[client] connected to pipe");
Console.WriteLine("[client] There are currently {0} pipe server instances open.",pipeClient.NumberOfServerInstances); StreamWriter writer = new StreamWriter(pipeClient);
writer.AutoFlush = true;
StreamReader reader = new StreamReader(pipeClient); String temp = "";
while (true) {
temp = Console.ReadLine(); //send to server
writer.WriteLine(temp); pipeClient.WaitForPipeDrain(); //read from server
Console.WriteLine("[client] read message from server:"+reader.ReadLine()); if (temp == "EXIT") {
break;
}
}
} Console.ReadLine();
}
}
}

PipeClient.cs

这里需要注意,"."代表本机地址。如果需要到其他服务器,替换就好了。

【C#】解析C#中管道流的使用的更多相关文章

  1. linux命令中"|"管道流的意思

    在linux中.可以利用符号:"|"来实现管道功能. 那么什么是管道功能呢: 管道是Shell的一大特征.他将多个命令前后连接起来形成一个管道流. 管道流中的每一个命令都作为一个单 ...

  2. Java基础IO类之字符串流(查字符串中的单词数量)与管道流

    一.字符串流 定义:字符串流(StringReader),以一个字符为数据源,来构造一个字符流. 作用:在Web开发中,我们经常要从服务器上获取数据,数据返回的格式通常一个字符串(XML.JSON), ...

  3. Java中的管道流 PipedOutputStream和PipedInputStream

    我们在学习IO流的时候可能会学字节流.字符流等,但是关于管道流的相信大部分视频或者教程都是一语带过,第一个是因为这个东西在实际开发中用的也不是很多,但是学习无止境,存在既有理.JDK中既然有个类那说明 ...

  4. node.js 从文件流中读写数据及管道流

    读取数据 // 引入 fs 模块 const fs = require('fs'); // 创建可读流 let readStream = fs.createReadStream('index.txt' ...

  5. MVC5-2 MVC的管道流与路由

    自定义Modue与Hander 之前讲了管道流中的Module与Hndler.现在我们可以去自定义Module和Handler Module 其实很简单,一共需要三个步骤 定义一个类去继承IHttpM ...

  6. node.js中stream流中可读流和可写流的使用

    node.js中的流 stream 是处理流式数据的抽象接口.node.js 提供了很多流对象,像http中的request和response,和 process.stdout 都是流的实例. 流可以 ...

  7. JAVA中管道通讯(线程间通讯)例子

    Java I/O系统是建立在数据流概念之上的,而在UNIX/Linux中有一个类似的概念,就是管道,它具有将一个程序的输出当作另一个程序的输入的能力.在Java中,可以使用管道流进行线程之间的通信,输 ...

  8. Java IO7:管道流、对象流

    前言 前面的文章主要讲了文件字符输入流FileWriter.文件字符输出流FileReader.文件字节输出流FileOutputStream.文件字节输入流FileInputStream,这些都是常 ...

  9. [Node.js] Node.js中的流

    原文地址:http://www.moye.me/2015/03/29/streaming_in_node/ 什么是流? 说到流,就涉及到一个*nix的概念:管道——在*nix中,流在Shell中被实现 ...

随机推荐

  1. 工作记录之 [ python请求url ] v s [ java请求url ]

    背景: 模拟浏览器访问web,发送https请求url,为了实验需求需要获取ipv4数据包 由于不做后续的内容整理(有内部平台分析),故只要写几行代码请求发送https请求url列表中的url即可 开 ...

  2. HDU 5409 CRB and Graph 【点双连通+DFS】

    <题目链接> 题目大意: 给你一个连通的无向图,问你删除每一条边后,是否能够出现一对(u,v),使得u,v不连通,且u<v,如果有多对u,v,则输出尽量大的u,和尽量小的v. 解题分 ...

  3. Springboot定时任务原理及如何动态创建定时任务

    一.前言 上周工作遇到了一个需求,同步多个省份销号数据,解绑微信粉丝.分省定时将销号数据放到SFTP服务器上,我需要开发定时任务去解析文件.因为是多省份,服务器.文件名规则.数据规则都不一定,所以要做 ...

  4. JVM之对象分配:栈上分配 & TLAB分配

    1. Java对象分配流程 2. 栈上分配 2.1 本质:Java虚拟机提供的一项优化技术 2.2 基本思想: 将线程私有的对象打散分配在栈上 2.3 优点: 2.3.1 可以在函数调用结束后自行销毁 ...

  5. python网站开发准备ubuntu14.04安装mysql实现windows管理

    sudo apt-get install mysql-server mysql-client 输入root密码 然后确认安装tab选定确认 输入数据库密码 重复输入 启动 sudo service m ...

  6. git SourceTree 客户端 安装/使用教程

    使用过SourceTree 之后发现比乌龟好多了 风来了.fox 1.安装之前的必备 1.1 git 客户端 http://msysgit.github.io/ 安装就PASS了,总之是直接下一步.直 ...

  7. 服务端spark gbdt模型计算性能优化

    服务端使用训练出来的模型,spark模型计算第一步是实现spark模型加载. 线上服务对用户体验影响极大,故需要对模型使用进行优化. 1.多线程并发进行计算,线上两个服务.优化cpu 2.在扩召回集, ...

  8. 使用 TestNG 测试的时候事务总是roll back的解决办法

    为要测试方法加上 @Rollback(false) 注解

  9. python之socket编程3

    1 什么是粘包 只有TCP有粘包现象,UDP永远不会粘包 应用程序所看到的数据是一个整体,或说是一个流(stream),一条消息有多少字节对应用程序是不可见的,因此TCP协议是面向连接的,面向流的,收 ...

  10. elastic-job详解(三):Job的手动触发功能

    elastic-job的任务都是使用quartz来触发的,quartz表达式一般都是定期执行.但有时候一些周期较长的任务,比如一天一次,几小时一次的任务,我们需要等待很久才能触发一次.如果我们需要测试 ...