C#命名管道

2 篇文章 0 订阅

近期做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();
		}
	}
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值