2012-02-02 14 views
18

NamedPipeServerStreamとNamedPipeServerClientが(それぞれPipeDirection = PipeDirection.InOutの場合)NamedPipeServerStreamとNamedPipeServerClientがメッセージを送信できる優れたサンプルを探しています。今のところはthis msdn articleしか見つかりませんでした。しかしそれはサーバだけを記述します。誰もこのサーバに接続するクライアントがどのように見えるかを知っていますか?NamedPipeServerStreamのサンプルとNamedPipeServerClientがPipeDirection.InOutを必要とする

答えて

33

サーバーは接続を待っていますが、単純なハンドシェイクとして「Waiting」という文字列を送信すると、クライアントはこれを読み取り、「Test Message」の文字列を返します私のアプリでは実際にはコマンドライン引数です)。

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); 
    } 
} 
+1

ありがとうございました!私のコードで何が問題であったかを理解するのを助けてくれました。私は、クライアントから別のスレッドで何かを読むのを待っているサーバを残していました。同時に、クライアントにメッセージを送信しようとしていました。コードはsw.WriteLineにぶら下がっていました。それは、サーバーがメッセージを待って、同じ時間に1つ送信することはできないようです。 – Nat

+0

シンプルで透明です。 +1 – Artiom

+0

これは私が見つけた最もシンプルでクリーンな(DllImportなし)ソリューションです。ありがとう! – Lensflare

関連する問題