2017-04-07 319 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。 –

相关问题