AnonymousPipeStream的使用具体案例如下:
服务端:
using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SupremeConsole
{
class Program
{
static void Main(string[] args)
{
#region 测试 NamedPipeStream
new Thread(new ThreadStart(AnonymousPipeServer)).Start();
#endregion
}
public static void AnonymousPipeServer()
{
string clientExe = @"F:\\Person\\Longteng\\LongtengSln\\ConsoleAppTestAnonymousPipe\\bin\\Debug\\ConsoleAppTestAnonymousPipe.exe";
HandleInheritability inherit = HandleInheritability.Inheritable;
using (var tx = new AnonymousPipeServerStream(PipeDirection.Out, inherit))
using (var rx = new AnonymousPipeServerStream(PipeDirection.In, inherit))
{
txID = tx.GetClientHandleAsString();
rxID = rx.GetClientHandleAsString();
var startInfo = new ProcessStartInfo(clientExe, txID + " " + rxID);
startInfo.UseShellExecute = false; // Required for child process
Process p = Process.Start(startInfo);
tx.DisposeLocalCopyOfClientHandle(); // Release unmanaged
rx.DisposeLocalCopyOfClientHandle(); // handle resources.
//tx.WriteByte(100);
//Console.WriteLine("Server received: " + rx.ReadByte());
//p.WaitForExit();
while (true)
{
tx.WriteByte();
Console.WriteLine("Server received: " + rx.ReadByte());
}
}
}
}
}
客户端(新建一个控制台程序):
using System;
using System.IO.Pipes;
using System.Threading;
namespace ConsoleAppTestAnonymousPipe
{
class Program
{
static void Main(string[] args)
{
string rxID = args[]; // Note we're reversing the
string txID = args[]; // receive and transmit roles.
using (var rx = new AnonymousPipeClientStream(PipeDirection.In, rxID))
using (var tx = new AnonymousPipeClientStream(PipeDirection.Out, txID))
{
//Console.WriteLine("Client received: " + rx.ReadByte());
//tx.WriteByte(200);
while (true)
{
Console.WriteLine("Client received: " + rx.ReadByte());
tx.WriteByte();
Thread.Sleep(TimeSpan.FromSeconds());
}
}
}
}
}
运行结果:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章