为什么NamedPipeClientStream给出访问被拒绝的错误?

时间:2019-01-29 18:34:44

标签: c# named-pipes namedpipeserverstream

我是NamedPipe的新手。我正在.Net Core 2.0中创建两个应用程序(客户端和服务器)。

在服务器中,我使用NamedPipeServerStream,在客户端中,我使用NamedPipeClientStream。

当我打开服务器流PipeDirection作为PipeDirection.InOut时,客户端流能够与服务器连接。 但是,当我打开服务器流PipeDirection作为PipeDirection.In或PipeDirection.Out时,客户端流会给出

的异常
System.UnauthorizedAccessException: 'Access to the path is denied.'

有人可以告诉我原因吗?预先感谢大家。

让我分享代码:

客户代码:

namespace ClientNamedPipe
{
    class Program
    {
        private static NamedPipeClientStream _clientStream = new NamedPipeClientStream("testPipe");
        private static byte[] _buffer = new byte[1024];

        static void Main(string[] args)
        {
            Console.Title = "Client";
            Console.WriteLine("Connecting to Server...");
            Connect();
            Console.ReadLine();
        }

        private static void Connect()
        {
            try
            {
                _clientStream.Connect();
                Console.WriteLine("Client Connected");
                ReadResponse();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Cannot connect client... \n" + ex.StackTrace);
            }
        }

        private static void ReadResponse()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            var data= (ReadResultResponse[])formatter.Deserialize(_clientStream);            
        }

    }
}

服务器代码:

namespace ServerNamedPipe
{
    class Program
    {
        private static NamedPipeServerStream _serverStream = new NamedPipeServerStream("testPipe", PipeDirection.In, 1);

        static void Main(string[] args)
        {
            Console.Title = "Server";
            Console.WriteLine("Waiting for client to connect");
            var thread = new Thread(() => Connect());
            thread.Start();
            //Connect();
            Console.ReadLine();
        }

        private static void Connect()
        {
            try
            {
                _serverStream.WaitForConnection();
                Console.WriteLine("Client Connected");
                SendResponse();
            }
            catch(Exception ex)
            {
                Console.WriteLine("Cannot connect with client...\n" + ex.StackTrace);
            }
        }

        private static void SendResponse()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            var responseList = new List<ReadResultResponse>();
            for(int i=0;i<10;i++)
            {
                var response = new ReadResultResponse { HasSuccceded = true, Response = "11", TimeOfResponse = DateTime.Now };
                responseList.Add(response);
            }
            formatter.Serialize(_serverStream, responseList.ToArray());
        }
    }
}

0 个答案:

没有答案