2017-08-04 73 views
1

我有一個程序使用TCPClient和網絡流接收來自外部IP的消息。不斷髮送消息,程序將這些消息轉換爲用戶可讀的格式。無法同時寫入和讀取到網絡流c#

但是,IP需要每8秒收到一次保持活動消息以保持連接處於打開狀態。

我似乎很難閱讀消息,並同時寫入流。只要他們處於不同的線索中,我就可以讀取和寫入流中的印象。

一旦計時器過去,並且調用寫入保持活動消息的方法,就會出現以下錯誤:無法從傳輸連接讀取數據:建立的連接被主機中的軟件中止。當寫入流方法被調用後,它在嘗試讀取一個字節時發生此錯誤。

以下是我的代碼。這是主要的:

public MainWindow() 
    { 
     InitializeComponent(); 

     client.Connect(address, port); 
     nwStream = client.GetStream(); 

     System.Timers.Timer newTimer = new System.Timers.Timer(8000); 
     newTimer.Elapsed += delegate { KeepAlive(nwStream, newTimer); }; 
     newTimer.Start(); 
     Thread t = new Thread(ReadInandOutputToTextBoxIfInvoke); 
     t.Start(); 
    } 

這裏是螺紋和方法,其從該流讀取:

private void ReadInandOutputToTextBoxIfInvoke() 
    { 

     while (run) 
     { 
      string message = ""; 
      int x = 0; 
      int start = 35; 
      int messageLength; 
      int numberOfMessages; 

      // NetworkStream nwStream = client.GetStream(); 
      try 
      { 
       while ((x = nwStream.ReadByte()) != start) { if (x == -1) { continue; } } //if it doesnt begin with # or has gone over then break 

       //reads in message header which is length then number of messages 
       messageLength = nwStream.ReadByte(); 
       numberOfMessages = nwStream.ReadByte(); 

       string messageRecieved = new string(readMessage(nwStream, messageLength - 1)); 
       string[] messages = messageRecieved.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); 


       for (int i = 0; i < numberOfMessages; i++) 
       { 
        string messageToProcess = messages[i]; 
        char messageType = messageToProcess[0]; 

我除去意爲它不是相應和所述消息方法的塊。

這是當定時器時間這就是所謂的代碼:

private void KeepAlive(NetworkStream Ns, System.Timers.Timer MyTimer) 
    { 
     byte[] toSend = new byte[] { 35, 51, 49, 42, 124 }; 
     try 
     { 
      for (int i = 0; i < toSend.Length; i++) 
      { 
       Ns.WriteByte(toSend[i]); 
       Ns.Flush(); 
      } 
     } 
     catch 
     { 
      MyTimer.Close(); 
     } 
    } 
+1

我很困惑,爲什麼你需要每隔8秒發送一條消息來保持連接的活着,這是每隔8秒鐘聽一次嗎? – Jaxi

+1

@Jaxi我正在說話的設備在設定的時間內沒有收到保持活動消息時關閉連接 –

+0

可能使用鎖定可能有幫助嗎? –

回答

1

現在我已經解決了我的問題。有兩個因素阻止程序正常工作。

  1. 使用鎖定後,錯誤停止顯示。
  2. 我被髮送到設備的信息是不正確的格式 - 它必須是十六進制

現在的作品完美。感謝所有想要幫助的人。