⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 namedpipes.cs

📁 通过NamePipe与其他进程通信的代码
💻 CS
字号:
using System;
using System.Runtime.InteropServices;
using System.Threading;

using NamedPipeAPIS;

namespace WindowsApplication1
{
	/// <summary>
	/// NamedPipes 的摘要说明。
	/// </summary>
	public class PipeServer:IDisposable
	{
		private bool _listen = true;
		private Thread MainThread;
		private IntPtr FHandle;
		private string FPipeName;
		private uint OutBuffer = 512;
		private uint InBuffer = 512;
		private string ErrorText;
		public PipeServer()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}
		public bool Opened{
			get{return (this.MainThread.ThreadState==ThreadState.Running);}
		}
		public bool Initialize(string aServer,string aPipe) 
		{
			if (aServer == "") 
			{
				FPipeName = string.Format("\\\\{0}\\pipe\\{1}", '.', aPipe);
			}
			else
			{
				FPipeName =string.Format("\\\\{0}\\pipe\\{1}",aServer, aPipe);
			}
			if (NamedPipeAPI.WaitNamedPipe(FPipeName, 100))
			{
				ErrorText= "合名管道已存在";
				return false;
			}
			FHandle=NamedPipeAPI.CreateNamedPipe(
				FPipeName,
				NamedPipeAPI.PIPE_ACCESS_DUPLEX,
				NamedPipeAPI.PIPE_TYPE_MESSAGE | NamedPipeAPI.PIPE_READMODE_MESSAGE | NamedPipeAPI.PIPE_WAIT,
				NamedPipeAPI.PIPE_UNLIMITED_INSTANCES,
				OutBuffer,
				InBuffer,
				NamedPipeAPI.NMPWAIT_WAIT_FOREVER,
				IntPtr.Zero);
			if (FHandle.ToInt32() != NamedPipeAPI.INVALID_HANDLE_VALUE) 
			{
				ErrorText="";				
			}
			else
			{
				ErrorText="不能启动管道";
				return false;
			}
			MainThread = new Thread(new ThreadStart(Start));
			MainThread.Name = "PDM Pipe Thread";
			MainThread.Start();
			Thread.Sleep(1000);
			return true;
		}
		private void Start() 
		{
			try 
			{
				while (_listen) 
				{
					if (FHandle.ToInt32()== NamedPipeAPI.INVALID_HANDLE_VALUE)
					{
						System.Threading.Thread.Sleep(250);
					}
					else
					{
						if (NamedPipeAPI.ConnectNamedPipe(FHandle,null))
						{
							try
							{
								byte[] numReadWritten = new byte[4];
								byte[] bytes=new byte[8108];
								NamedPipeAPI.ReadFile(FHandle,bytes,8108,numReadWritten,0);
								try
								{
									RPIPEMessage inMsg=RPIPEMessage.GetMessage(bytes);
									RPIPEMessage outMsg=new RPIPEMessage(1,"OK");
									NamedPipeAPI.WriteFile(FHandle,outMsg.GetBytes(),outMsg.Size,numReadWritten,0);
									if (inMsg.Kind==0)
									{
										_listen=false;
									}
									ErpMessage msg=new ErpMessage(inMsg.Kind,new string(inMsg.Data));
									this.OnPipeCallMessage(msg);
									//Form1.newForm.Text =new string(inMsg.Data);
								}
								catch
								{
								}
							}
							catch(Exception ex)
							{
								string a=ex.Message;
							}
							finally
							{
								NamedPipeAPI.DisconnectNamedPipe(FHandle);
							}
						}
						//System.Threading.Thread.Sleep(250);
					}
				}
			}
			catch 
			{
				// Log exception
			}
		}
		public void Stop()
		{
			this._listen =false;
			RPIPEMessage msg=new RPIPEMessage(0,"Close");
			byte[] bts=new byte[4];
			byte[] bytes=new byte[8108];
			if (FHandle.ToInt32()!=NamedPipeAPI.INVALID_HANDLE_VALUE)
			{
				NamedPipeAPI.CallNamedPipe(FPipeName, msg.GetBytes(),msg.Size,bytes, 8108, bts, 100);
				NamedPipeAPI.CloseHandle(FHandle);
				// 清除handle
				FHandle=(IntPtr)NamedPipeAPI.INVALID_HANDLE_VALUE;
			}
			this.MainThread.Abort();
		}
		#region IDisposable 成员
        
		public void Dispose()
		{
			// TODO:  添加 PipeServer.Dispose 实现
            Stop();
		}

		#endregion
		#region 自定义事件
		public event PipeEventHandler PipeCallMessage;
		protected virtual void OnPipeCallMessage(ErpMessage e)
		{
			if(PipeCallMessage!=null) PipeCallMessage(this,e);
		}
		#endregion
	}
	#region 命名管道客户端
	/// <summary>
	/// 命名管道客户端
	/// </summary>
	public class PipeClient
	{
		private string FPipeName;
		private string ErrorTxt;
		public PipeClient(string aServer,string aPipe)
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
			if (aServer == "") 
			{
				FPipeName = string.Format("\\\\{0}\\pipe\\{1}", '.', aPipe);
			}
			else
			{
				FPipeName =string.Format("\\\\{0}\\pipe\\{1}",aServer, aPipe);
			}
		}
		private bool ProccMsg( RPIPEMessage msg,ref RPIPEMessage reMsg )
		{
			
           
			if (NamedPipeAPI.WaitNamedPipe(FPipeName, 10))
			{		
				byte[] bytes=new byte[8108];
				byte[] bts=new byte[4];
				if (!NamedPipeAPI.CallNamedPipe(FPipeName, msg.GetBytes(),msg.Size,bytes, 8108, bts, 500))
				{
					ErrorTxt="连接不到命名管道";
					return false;
				}
				else
				{
					try
					{
						reMsg=RPIPEMessage.GetMessage(bytes);
						return true;
					}
					catch
					{
						return false;
					}
				}
			}
			else
			{
				ErrorTxt="命名管道不存在";
				return false;
			}
		}
		public string SendMessage(byte kind,string msgStr)
		{
			RPIPEMessage msg=new RPIPEMessage(1,msgStr);
			RPIPEMessage remsg=new RPIPEMessage(1,"失败");
			ProccMsg(msg,ref remsg);
			return new string(remsg.Data);
		}
	}
	#endregion
	#region 事件定义
		public delegate void PipeEventHandler(object sender,ErpMessage e);
	#endregion
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -