NamedPipeClient.cs 1.3 KB
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;


/// <summary>
/// 客户端管道
/// </summary>
public class NamedPipeClient
{
    private NamedPipeClientStream Client { get; set; }

    public NamedPipeClient(string serverName, string serverHost)
    {
        Client = new NamedPipeClientStream(serverHost, serverName);

    }
    byte[] readBytes = new byte[1024*50];
    public string Request(string outPutStr)
    {
        string inputStr = "";
        try
        {

            this.Client.Connect(1000*5);
            var b = Encoding.UTF8.GetBytes(outPutStr);

            this.Client.Write(b, 0, b.Length);
            this.Client.Flush();
            Client.WaitForPipeDrain();
            int readlen = Client.Read(readBytes, 0, readBytes.Length);
            while (readlen > 0)
            {
                inputStr += Encoding.UTF8.GetString(readBytes, 0, readlen);
                readlen = Client.Read(readBytes, 0, readBytes.Length);
            }
        }
        catch { }
        finally
        {
            if (Client.IsConnected)
                Client.Close();
        }
        
        //this.Client.Dispose();

        return inputStr;
    }

}