C# 命名管道进程间通信

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.Security.Principal;

namespace TopInfo.Metevation.Common
{
    public class PipeMessageUtil
    {
        private const string PipeName = "TopInfoPipe";

        public static bool NeedSendMessage = false;

        private static NamedPipeServerStream pipeServer;

        private static NamedPipeClientStream pipeClient;

        public static void OpenPiepServer()
        {
            if (pipeServer == null)
            {
                pipeServer = new NamedPipeServerStream(PipeName,
                                    PipeDirection.Out, 1,
                                    PipeTransmissionMode.Byte,
                                    PipeOptions.Asynchronous);

                pipeServer.BeginWaitForConnection(
                    delegate
                    {
                        NeedSendMessage = true;
                        pipeServer.WaitForConnection();
                        //pipeServer.EndWaitForConnection();
                    },
                    null);
            }
        }

        public static void ClosePipeServer()
        {
            if (pipeServer != null && pipeServer.IsConnected)
                pipeServer.Close();
            NeedSendMessage = false;
        }

        public static void SendMessage(string msg)
        {
            if (NeedSendMessage && pipeServer.IsConnected && pipeServer.CanWrite)
            {
                StreamString ss = new StreamString(pipeServer);
                ss.WriteString(msg);
            }
        }

        public delegate void PrintMessage(string msg);//委托接受消息处理方法

        public static void ReciverMessage(PrintMessage printMessage)
        {
            if (pipeClient == null)
            {
                pipeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.In, PipeOptions.None, TokenImpersonationLevel.None);
                pipeClient.Connect();
            }
            while (pipeClient.CanRead)
            {
                StreamString ss = new StreamString(pipeClient);
                printMessage(ss.ReadString());
            }
            pipeClient.Close();
        }
    }
}
posted @ 2011-05-20 16:35  Wythe  阅读(3665)  评论(1编辑  收藏  举报