C#命名管道通信
最近項目中要用c#進程間通信,以前常見的方法包括RMI、發消息等。但在Windows下面發消息需要有窗口,我們的程序是一個后台運行程序,發消息不試用。RMI又用的太多了,准備用管道通信來做消息通信。
管道通信以前在大學學過,包括匿名管道和命名管道。匿名管道只能用在父子進程之間;命名管道可以用在兩個進程甚至跨服務器通信。這里給出命名管道的示例。
服務器端代碼
private static void WaitData()
{
using (NamedPipeServerStream pipeServer =
new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1))
{
try
{
pipeServer.WaitForConnection();
pipeServer.ReadMode = PipeTransmissionMode.Byte;
using (StreamReader sr = new StreamReader(pipeServer))
{
string con = sr.ReadToEnd();
Console.WriteLine(con);
}
}
catch (IOException e)
{
throw e;
}
}
}
客戶端代碼
private static void SendData()
{
try
{
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None))
{
pipeClient.Connect();
using (StreamWriter sw = new StreamWriter(pipeClient))
{
sw.WriteLine("hahha");
sw.Flush();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
參考: