近期做C#的项目,对C#不熟。将学到的知识点当做笔记记下来。
命名管道,用来进程间通信,一个客户端一个服务端。客户端可以向服务端发送输入的字符串。
客户端:管道名为"testPipe"
using System;
using System.IO;
using System.IO.Pipes;
namespace PipeClient
{
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testPipe", PipeDirection.InOut); //创建命名管道
pipeClient.Connect(); //连接管道
StreamReader sr = new StreamReader(pipeClient);
var data = new byte[1024];
data = System.Text.Encoding.Default.GetBytes("send to server:"); //向服务器端发送byte数组
pipeClient.Write(data, 0, data.Length);
string temp = sr.ReadLine(); //从服务器读取数据
Console.WriteLine(temp);
while(true)
{
StreamWriter writer = new StreamWriter(pipeClient);
Console.WriteLine("SendMessage:");
var Input = Conole.ReadLine(); //输入要发送的字符串
writer.WriteLine(Input); //向服务器端发送string字符串
writer.Flush(); //清空发送buffer
if (Input.Equals("quit")) //输入quit时结束通信
{
break;
}
temp = sr.ReadLine(); //从服务器读取数据
Console.WriteLine("Get Message:" + temp);
}
}
}
}
服务端:
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
namespace PipeServer
{
class Program
{
static void Main(string[] args)
{
NamedPipeServerStream pipeServer = new NamedPipeServerStream("testPipe", PipeDirection.InOut); //创建命名管道
pipeServer.WaitForConnection(); //等待连接
var data = new byte[10240];
while (true)
{
var count = pipeServer.Read(data, 0, 10240); //读取byte类型数据,返回读取的长度
string recvData = Encoding.Default.GetString(data, 0, count).Trim();
if (recvData.Equals("quit"))
{
break;
}
try{
StreamWriter sw = new StreamWriter(pipeServer);
sw.AutoFlush = true;
sw.WriteLine("send to client"); //向客户端发送数据
}
catch(Exception ex)
{
Console.WriteLine("connection failed." + ex.ToString());
pipeServer.WaitForCOnnection(); //断开重连
}
if (count == 0) //非阻塞读取,读取不到数据时继续读
{
continue;
}
Console.WriteLine("Get data from client:" + recvData);
}
pipeServer.Close();
}
}
}