佳佳的博客
Menu
首页
《.NET Core 实战》 [No.265~266] 命名管道
Posted by
佳佳
on 2020-03-27
IT
C#
.NET Core
《.NET Core 实战》
读书笔记
<!-- # 《.NET Core 实战》 [No.265~266] 命名管道 --> <!-- dotnet-core-named-pipe --> **命名管道**是一种比较简单易用的通信方式,**它支持同一台计算机上进程与进程之间,或者不同计算机上进程与进程之间的数据传输。** 需要用到 *System.IO.Pipes* 命名空间下的两个类: 1. `NamedPipeServerStream` 类 通信中的服务器。 实例化时可以通过 *direction* 参数传入一个 `PipeDirection` 枚举来指定管道的通信方法。默认值为 *PipeDirection.InOut* 双向通信。 实例化后需要调用 *WaitForConnection* 或 *WaitForConnectionAsync* 方法来侦听客户端连接。 2. `NamedPipeClientStream` 类 通信中的客户端。 实例化时可以通过 *serverName* 参数指定远程计算机的名称。本机测试时可以指定为 *.* 或 *localhost* 。 实例化时可以通过 *direction* 参数传入一个 `PipeDirection` 枚举来指定管道的通信方法。默认值为 *PipeDirection.InOut* 双向通信。 实例化后需要调用 *Connect* 方法向服务器发起连接请求。 上面提到的枚举 `PipeDirection` 有以下三个值: - *Out*:管道仅为输出模式,即只能写入消息。 - *In*:管道仅为输入模式,即只能读取消息。 - *InOut*:双向通信,既可以写入消息,也可以读取消息。 **这两个类都是 `Stream` 的派生类,因此它们都可以以流的方式发送或接收数据。** 下面示例展示的是一个**单向通信**,服务器只能发送消息,客户端只能接收消息。 ## 1. 服务器 ```csharp using (NamedPipeServerStream server = new NamedPipeServerStream("demo", PipeDirection.Out)) { Console.WriteLine("服务器管道已创建。"); // 等待客户端的连接 server.WaitForConnection(); Console.WriteLine("正在等待客户端连接......"); using (StreamWriter writer = new StreamWriter(server)) { writer.AutoFlush = true; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("注意:可输入\"end\"退出。"); Console.ResetColor(); while (true) { Console.WriteLine("请输入要发送的内容:"); string msg = Console.ReadLine(); if (!string.IsNullOrEmpty(msg)) { if (msg.ToLower() == "end") { break; } writer.WriteLine(msg); } } } } ``` ## 2. 客户端 ```csharp using (NamedPipeClientStream client = new NamedPipeClientStream(".", "demo", PipeDirection.In)) { Console.WriteLine("即将连接服务器。"); client.Connect(); Console.WriteLine("连接成功。"); try { using (StreamReader reader = new StreamReader(client)) { string msg = null; while ((msg = reader.ReadLine()) != null) { Console.WriteLine($"服务器:{msg}"); } } } catch (Exception ex) { Console.WriteLine($"发生了异常:{ex}"); } } ``` ## 运行结果   --- > 购买本书 => [《.NET Core实战:手把手教你掌握380个精彩案例》][10] -- *周家安* 著 --- [10]:https://union-click.jd.com/jdc?e=&p=AyIGZRhaEwAQBFUZXBIyEgRSEl0QCxc3EUQDS10iXhBeGlcJDBkNXg9JHU4YDk5ER1xOGRNLGEEcVV8BXURFUFdfC0RVU1JRUy1OVxUBFQ5THlIQMm1AEkRdb11GZyNTK0BBZwYIbylWcHILWStaJQITBlYbXB0LFQJlK1sSMkBpja3tzaejG4Gx1MCKhTdUK1sRCxQBVxtTEQIQBlwrXBULIloNXwZBXUReEStrJQEiN2UbaxYyUGlUG1kUBhcGUBILQgUXDlMeUkBVRlUBS10XBkIABhkJRzIQBlQfUg%3D%3D (《.NET Core实战:手把手教你掌握380个精彩案例》)
版权声明:原创文章,未经允许不得转载。
https://www.liujiajia.me/2020/3/27/dotnet-core-named-pipe
“Buy me a nongfu spring”
« 《.NET Core 实战》 [No.267~283] 序列化
《.NET Core 实战》 [No.263~264] 内存映射文件 »
Commented by
lindexi
on 2020-10-19
回复
其实管道是半工,也就是在读取的时候不能发送,在发送的时候不能读取。同时只能使用读或写,但是在读取完成之后就可以写入
昵称
*
电子邮箱
*
回复内容
*
(回复审核后才会显示)
提交
目录
AUTHOR
刘佳佳
江苏 - 苏州
软件工程师
梦嘉集团
lindexi
on 2020-10-19 回复