前提・実現したいこと
https://qa.atmarkit.co.jp/q/3331
のコードを元にクライアント<=>サーバーの双方向通信に変更したい
ここに質問の内容を詳しく書いてください。
上記HPのコードを元に双方向に変更してみたのですが、サーバー側でのメッセージ受信後の
メッセージ送信時に「パイプが壊れています。」となり動作しません。
よろしくお願いします。
該当のソースコード
C#
1 2**サーバ側** 3ThreadState s = ThreadState.Stopped; 4 String pipeServerName = "pipeServerName"; 5 6 private void button1_Click(object sender, EventArgs e) 7 { 8 Thread t = new Thread(new ThreadStart(Method1)); 9 s = ThreadState.Running; 10 t.Start(); 11 } 12 13 private void Method1() 14 { 15 List<string> listInputDatas = new List<string>(); 16 string inputData = String.Empty; 17 18 while (true) 19 { 20 using (var pipeServer = new NamedPipeServerStream(pipeServerName, PipeDirection.InOut)) 21 { 22 using (var sr = new StreamReader(pipeServer)) 23 using (var sw = new StreamWriter(pipeServer)) 24 { 25 try 26 { 27 if (pipeServer.IsConnected == false) 28 { 29 pipeServer.WaitForConnection(); 30 } 31 32 //信号受信 33 inputData = sr.ReadLine(); 34 listInputDatas.Add((inputData)); 35 System.Diagnostics.Debug.Print(inputData); 36 } 37 catch (Exception Ex) 38 { 39 string ex = Ex.Message; 40 } 41 42 try 43 { 44 if (pipeServer.IsConnected == false) 45 { 46 pipeServer.WaitForConnection(); 47 } 48 49 sw.AutoFlush = true; 50 sw.Write("OK:" + inputData); //ここで例外発生「パイプが壊れています。」 51 sw.Flush(); 52 pipeServer.WaitForPipeDrain(); 53 } 54 catch(Exception Ex) 55 { 56 string ex = Ex.Message; 57 } 58 } 59 } 60 // その他終了判定など 61 if (s == ThreadState.Stopped) return; 62 } 63 } 64 65クライアント側 66// 名前かえました 67 String pipeServerName = "pipeServerName"; 68 69 private void btnStart_Click(object sender, EventArgs e) 70 { 71 var sb = new StringBuilder(); 72 73 // PIPEで送信する 74 using (var pipeClient = new NamedPipeClientStream("localhost", pipeServerName, PipeDirection.InOut, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Impersonation)) 75 { 76 string inputData = String.Empty; 77 78 sb.AppendLine(DateTime.Now.ToString() + "\t" + textBox1.Text); 79 80 try 81 { 82 pipeClient.Connect(); 83 } 84 catch (Exception Ex) 85 { 86 87 } 88 89 using (var sw = new StreamWriter(pipeClient)) 90 { 91 sw.AutoFlush = true; 92 sw.Write(sb); 93 //sw.Flush(); 94 pipeClient.WaitForPipeDrain(); 95 } 96 97 98 using (var sr = new StreamReader(pipeClient)) 99 { 100 inputData = sr.ReadLine(); 101 } 102 103 } 104 } 105 106
補足情報(FW/ツールのバージョンなど)
VS2017
.net3.5
ここにより詳細な情報を記載してください。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。