C#的命名管道(named pipe)
命名管道是一种从一个进程到另一个进程用内核对象来进行信息传输。和一般的管道不同,命名管道可以被不同进程以不同的方式方法调用(可以跨权限、跨语言、跨平台)。只要程序知道命名管道的名字,发送到命名管道里的信息可以被一切拥有指定授权的程序读取,但对不具有制定授权的。命名管道是一种FIFO(先进先出,First-In First-Out)对象。
我们可以使用命名管道在2个不同的进程中进行通信而不需要通过一般的IO读写文件来获取信息。
在C#中可以简单的这么用用来接收消息
using System.IO.Pipes; private volatile NamedPipeServerStream _OutputNamedPipe;
_OutputNamedPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 254); private void BeginReceiveOutput() { try { _OutputNamedPipe.WaitForConnection(); using (var reader = new StreamReader(_OutputNamedPipe)) { _OutputMessage = reader.ReadLine(); } } catch { } }
在vbscript里可以这样来发消息
Dim fs, pipe Set fs = CreateObject("Scripting.FileSystemObject") Set pipe = fs.OpenTextFile("\\.\pipe\PipeName", 8, False, 0) pipe.WriteLine("This is a message from vbs") pipe.Close
更为严谨的写法
1 class Server 2 { 3 static void Main(string[] args) 4 { 5 var running = true; 6 7 while (running) // loop only for 1 client 8 { 9 using (var server = new NamedPipeServerStream("PIPE_NAME", PipeDirection.InOut)) 10 { 11 server.WaitForConnection(); 12 13 Console.WriteLine("Client connected"); 14 15 using (var pipe = new PipeStream(server)) 16 { 17 pipe.Send("handshake"); 18 19 Console.WriteLine(pipe.Receive()); 20 21 server.WaitForPipeDrain(); 22 server.Flush(); 23 } 24 } 25 } 26 27 Console.WriteLine("server closed"); 28 Console.Read(); 29 } 30 } 31 32 class Client 33 { 34 static void Main(string[] args) 35 { 36 using (var client = new NamedPipeClientStream(".", "PIPE_NAME", PipeDirection.InOut)) 37 { 38 client.Connect(2000); 39 40 using (var pipe = new PipeStream(client)) 41 { 42 Console.WriteLine("Message: " + pipe.Receive()); 43 44 pipe.Send("Hello!!!"); 45 } 46 } 47 48 Console.Read(); 49 } 50 } 51 52 public class PipeStream : IDisposable 53 { 54 private readonly Stream _stream; 55 private readonly Reader _reader; 56 private readonly Writer _writer; 57 58 public PipeStream(Stream stream) 59 { 60 _stream = stream; 61 62 _reader = new Reader(_stream); 63 _writer = new Writer(_stream); 64 } 65 66 public string Receive() 67 { 68 return _reader.ReadLine(); 69 } 70 71 public void Send(string message) 72 { 73 _writer.WriteLine(message); 74 _writer.Flush(); 75 } 76 77 public void Dispose() 78 { 79 _reader.Dispose(); 80 _writer.Dispose(); 81 82 _stream.Dispose(); 83 } 84 85 private class Reader : StreamReader 86 { 87 public Reader(Stream stream) 88 : base(stream) 89 { 90 91 } 92 93 protected override void Dispose(bool disposing) 94 { 95 base.Dispose(false); 96 } 97 } 98 99 private class Writer : StreamWriter 100 { 101 public Writer(Stream stream) 102 : base(stream) 103 { 104 105 } 106 107 protected override void Dispose(bool disposing) 108 { 109 base.Dispose(false); 110 } 111 } 112 }