C#命名管道:服务器和客户端关系

时间:2019-07-26 21:37:00

标签: c# named-pipes

在探索如何在C#中实现命名管道时,我遇到了意外的行为。我的测试涉及两个控制台应用程序ServerApp和ClientApp,它们通过命名管道进行通信。 ServerApp实现NamedPipeServerStream,而ClientApp实现NamedPipeClientStream。他们建立联系并进行交流,但是我注意到的行为是这样的:

  • 启动ServerApp
  • 启动ClientApp
  • 两者都预订了收到消息时触发的事件
  • 两个人都坐在Console.ReadLine()命令中,等待用户向其他应用输入消息
  • ServerApp发送消息,在ClientApp中触发消息接收事件,中断ReadLine命令
  • ClientApp发送一条消息,ServerApp停留在ReadLine命令中,直到用户输入完成ReadLine的值后才触发消息接收事件

服务器消息是否可以打断客户端,但不能反过来阻止客户的这种行为?

服务器代码,除了使用ClientPipe之外,与客户端相同

class Program
    {
        private static ServerPipe server;
        static void Main(string[] args)
        {
            Console.Title = "Server";
            string name = "test_pipe";
            server = new ServerPipe(name);
            server.MessageRecieved += Server_MessageRecieved;
            AskForInput();
        }

        private static void Server_MessageRecieved(PipeEventArgs e)
        {
            Console.WriteLine($"\nClient Says --> {e.Data}");
            server.OpenPipe();
           AskForInput();
        }

        private static void AskForInput()
        {
            Console.Write("\nMessage for Client: ");
            string message = Console.ReadLine();
            server.WriteStream(message);
            AskForInput();
        }
    }

OpenPipe启动管道的异步读取

public async void OpenPipe()
        {
            while (!pipe.IsConnected)
            {

            }
            while (true)
            {
                string message = string.Empty;
                byte[] buffer = new byte[1];
                int i = 0;
                do
                {
                    i = await pipe.ReadAsync(buffer, 0, buffer.Length);
                    message = message + Encoding.ASCII.GetString(buffer);
                    buffer = new byte[1];
                }
                while (!pipe.IsMessageComplete);
                if (message != string.Empty)
                {
                    PipeEventArgs a = new PipeEventArgs(this, message);
                    MessageRecieved(a);
                }
            }
        }

example of interaction from client and server perspectives

0 个答案:

没有答案