2017-04-07 264 views
-3

這是錯誤:C#TCP客戶端發送消息,但服務器未接收到該消息

**

拋出異常: 'System.InvalidOperationException' 在 System.Windows.Forms的。 dll附加信息:跨線程 操作無效:通過線程 以外的線程訪問控制'displayText',而不是創建它的線程。

**

我已創建使用C#的多線程客戶端和服務器應用程序。我研究了這個錯誤,但是我找不到任何相關的答案。我知道這是在程序啓動兩個或多個線程時發生的......但是我的服務器端有一個線程......我不知道爲什麼會出現這種情況..........

這裏是我的服務器端:

 private void Handler() 
     { 
      try { 


       byte[] b = new byte[100]; 
       int k = s.Read(b, 0, b.Length); 

       //int k = s.Receive(b); 



       string szReceived = Encoding.ASCII.GetString(b,0,k); 
       //If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, 


       while (ServerRunning) 
       { 
        string ConcatString = ""; 
        for (int i = 0; i < k; i++) 
        { 

         char n = Convert.ToChar(b[i]); 
         string chars = Convert.ToString(n); 
         ConcatString = ConcatString + chars; 

        } 

        if (b[0] == '$') 
        { 
         displayText.AppendText("\nPrivate Message"); 
         //MessageBox.Show("\nPrivate Message" + Environment.NewLine); 
        } 
        else 
        { 
         displayText.AppendText("\n" + ConcatString); 
         //MessageBox.Show(ConcatString + Environment.NewLine); 
        } 

        //Encoding is the process of transforming a set of Unicode characters into a sequence of bytes and using new instance 
        ASCIIEncoding asen = new ASCIIEncoding(); 

        //s.Send(asen.GetBytes("The string was recieved by the server." + Environment.NewLine)); 

        displayText.AppendText("\n" + ConcatString); 
        /* clean up */ 
        //* 
        // k = s.Receive(b); 
        s.Close(); 
        client.Close(); 
        //MessageBox.Show("Recieved..." + Environment.NewLine); 


       } 
      } 
      catch(Exception ex) 
      { 
       MessageBox.Show("Error ...." + ex); 
      } 
     } 

我是新來的Socket編程,但我研究每一個代碼段,並在幾次嘗試的代碼..還是無法弄清楚究竟是什麼我錯過了在這程序...

所以請幫我解決這個問題...我將非常感激... 謝謝..

+1

你得到的錯誤是因爲你試圖從另一個線程更新你不能做的UI,我不相信它沒有收到消息,這篇文章的標題和正文不匹配 – BugFinder

+0

你的服務器正在接收消息,但你試圖從另一個線程訪問'displayText'控件 - 你不能這樣做。 –

+0

看看@rene提到的問題,以及如何試着瞭解你的實際錯誤 - 注意它是如何提及套接字的... –

回答

1
Invoke((MethodInvoker) delegate { displayText.AppendText("\n" + ConcatString); }); 

應該修復它;將「附加到UI」代碼分派到UI線程並等待它完成。

+0

@PiyasenaSenani'Invoke'是'Form。 Invoke'方法,[here](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.invoke(v = vs.110).aspx); 'MethodInvoker'只是一個衆所周知的委託類型,它是由'Invoke'特殊的表現而不是'Delegate.DynamicInvoke'。基本上,它只是創建一個可運行的代碼片段,並說:「嘿,用戶界面:在我等待的時候爲我運行」 –

+2

@PiyasenaSenani再次,這有**無關套接字**,一切都與你的事實有關'從非UI線程觸摸界面 –

+0

@PiyasenaSenani當然是線程 - 這正是例外告訴你的;在這裏看到你的代碼:'Thread tcpHandlerThread = new Thread(Handler); tcpHandlerThread.Start();' - 在另一個線程上運行'Handler'方法***。該線程不允許直接觸摸UI。 –

相關問題