web-dev-qa-db-ja.com

NamedPipeServerStreamとPipeDirection.InOutが必要なNamedPipeServerClientのサンプル

NamedPipeServerStreamとNamedPipeServerClientが互いにメッセージを送信できる適切なサンプルを探しています(両方に対してPipeDirection = PipeDirection.InOutの場合)。今のところ私は このmsdnの記事 のみを見つけました。ただし、サーバーについてのみ説明します。誰かがこのサーバーに接続するクライアントがどのように見えるべきか知っていますか?

21
Nat

何が起こるかというと、サーバーは接続を待機している状態です。接続があると、サーバーは文字列「Waiting」を単純なハンドシェイクとして送信します。クライアントはこれを読み取ってテストし、「テストメッセージ」の文字列を送り返します(私のアプリでは実際にはコマンドライン引数)。

WaitForConnectionはブロックしているので、別のスレッドで実行することをお勧めします。

class NamedPipeExample
{

  private void client() {
    var pipeClient = new NamedPipeClientStream(".", 
      "testpipe", PipeDirection.InOut, PipeOptions.None);

    if (pipeClient.IsConnected != true) { pipeClient.Connect(); }

    StreamReader sr = new StreamReader(pipeClient);
    StreamWriter sw = new StreamWriter(pipeClient);

    string temp;
    temp = sr.ReadLine();

    if (temp == "Waiting") {
      try {
        sw.WriteLine("Test Message");
        sw.Flush();
        pipeClient.Close();
      }
      catch (Exception ex) { throw ex; }
    }
  }

同じクラス、サーバーメソッド

  private void server() {
    var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);

    StreamReader sr = new StreamReader(pipeServer);
    StreamWriter sw = new StreamWriter(pipeServer);

    do {
      try {
        pipeServer.WaitForConnection();
        string test;
        sw.WriteLine("Waiting");
        sw.Flush();
        pipeServer.WaitForPipeDrain();
        test = sr.ReadLine();
        Console.WriteLine(test);
      }

      catch (Exception ex) { throw ex; }

      finally {
        pipeServer.WaitForPipeDrain();
        if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
      }
    } while (true);
  }
}
35
Matt