如何继续从命名管道/流发送/读取消息

Bra*_*ore 6 .net c# stream named-pipes

我正在自学使用管道,我有两个应用程序,一个带有 PipeServer 类,另一个带有 PipeClient 类(如下所示)。服务器应用程序创建 PipeServer 的实例,并具有一个文本框,当文本框发生更改时,该文本框会调用 WriteMessage 方法。客户端应用程序创建 PipeClient 的实例,将 MessageReadEvent 设置为使用给定消息填充文本框的方法,然后调用 ReadMessages 方法。

第一次调用 ReadMessages 方法时,它会到达 sr.ReadLine() 并在那里等待,直到收到消息。收到消息后,下一次调用 sr.ReadLine() 自然会返回 null 并继续退出该方法。

此时,对 ReadMessages 的任何进一步调用都会出现异常,表明管道已关闭。我不确定我是否明白为什么管道会关闭。我如何保持它打开?我当然不必为每条要发送的消息创建一个新的管道实例吗?

下面是我的 PipeClient 类。如果有帮助的话,我也可以添加我的 PipeServer 类,但我认为问题出在此处......

    public delegate void MessageReadEventHandler(string message);

    class PipeClient: IDisposable
    {
        public event MessageReadEventHandler MessageReadEvent;

        NamedPipeClientStream _pipeClient;

        public PipeClient(string pipeName)
        {
            _pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.In);
            _pipeClient.Connect();
        }

        public void ReadMessages()
        {
            string temp;

            // Is _pipeClient getting disposed when sr gets disposed??
            // I wouldn't think so but I don't understand why I can't seem
            // to use it again after the following using statement is run

            using (StreamReader sr = new StreamReader(_pipeClient))
                while ((temp = sr.ReadLine()) != null)
                    if(MessageReadEvent != null)
                        MessageReadEvent(temp);
        }

        public void Dispose()
        {
            _pipeClient.Dispose();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Pav*_*ets 5

StreamReader 在处置后关闭传递给它的流,并且您在块的末尾处置 StreamReader using (StreamReader sr = new StreamReader(_pipeClient))

您可以在构造函数中在类级别创建 StreamReader,并在 ReadMessages 方法中使用它

  public PipeClient(string pipeName)
    {
        _pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.In);
        _pipeClient.Connect();
        _streamReader = new StreamReader(_pipeClient);
    }
  public void ReadMessages()
    {
        string temp;



            while ((temp = _streamReader.ReadLine()) != null)
                if(MessageReadEvent != null)
                    MessageReadEvent(temp);
    }
Run Code Online (Sandbox Code Playgroud)