2017-02-06 15 views
1

Привет, у меня есть аранжировка на моем NamedPipeServer.C# NamedPipeServer Broken после новой записи

Сервер и клиент работают нормально, если я использую один поток WriteLine и скрытый.

после того, как я попытаюсь написать новую строку, у меня ошибка IOException Pipe Broken.

Pipe Сервер трубы

NamedPipeServerStream 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); 

        if (test.Contains("Mouse")) 
        { 
         Invoke((Action)delegate 
          { 
           listBox1.Items.Add(test); 
           listBox1.SelectedIndex = listBox1.Items.Count - 1; 
          }); 
        } 

        if (test.Contains("Bt1")) 
        { 
         Invoke((Action)delegate 
         { 
          listBox2.Items.Add("BT"); 
         }); 
        } 

       } 

       catch (Exception ex) { throw ex; } 

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

Client

 NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", 
"testpipe", PipeDirection.InOut, PipeOptions.None); 
     private void Form1_MouseMove(object sender, MouseEventArgs e) 
     { 


      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 
       { 

        //First Write Working! 
        sw.WriteLine("Mouse Pos: " + e.Location); 
        sw.Flush(); 

        //Second Write i get Exception and Pipe Broken 
        sw.WriteLine("Bt1:1"); 
        sw.Flush(); 

        pipeClient.Close(); 
       } 
       catch (Exception ex) { throw ex; } 
      } 
     } 

Как исправить эту проблему?

ответ

2

Ваш сервер закрывает подключение после первой строки получено. Поэтому при отправке второй линии труба уже закрыта (или «сломана»).

Вы должны создать внутреннюю петлю на вашей стороне сервера и добавить какую-либо команду, чтобы закрыть Conn

NamedPipeServerStream 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(); 

     // start inner loop 
     while(pipeServer.IsConnected) 
     { 
      test = sr.ReadLine(); 
      Console.WriteLine(test); 

      if (test.Contains("Mouse")) 
      { 
       Invoke((Action)delegate 
       { 
        listBox1.Items.Add(test); 
        listBox1.SelectedIndex = listBox1.Items.Count - 1; 
       }); 
      } 

      if (test.Contains("Bt1")) 
      { 
       Invoke((Action)delegate 
       { 
        listBox2.Items.Add("BT"); 
       }); 
      } 

      // close command 
      if (test == "Close")     
       pipeServer.Disconnect();    
     } 
    } 
    catch (Exception ex) { throw ex; } 
    finally 
    { 
     //If i remove this line, The code Work 
     //pipeServer.WaitForPipeDrain(); 
     //if (pipeServer.IsConnected) { pipeServer.Disconnect(); } 
    } 
} while (true); 

Обратите внимание, что это не очень хороший дизайн, но может сделать для ваших целей тестирования. Вероятно, вы должны инкапсулировать обработку подключенного клиента в собственный метод или даже класс.

Обратите внимание, что catch(Exception ex) { throw ex; } несколько бесполезен (кроме вас, хочу, чтобы избавиться от первоначальной стоп-трассы).

+0

Я попробовал ваш пример Renè, но клиент замораживается. –

 Смежные вопросы

  • Нет связанных вопросов^_^