C#TCP客户端发送消息,但服务器未收到消息

时间:2017-04-07 09:50:19

标签: c# multithreading sockets tcp network-programming

这是错误:

**

  

抛出异常:'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 Programming的新手,但是我研究了每一个代码段并多次对代码进行了实验。仍然无法弄清楚我在这个程序中错过了什么......

所以请帮我解决这个问题......我将非常感激... 感谢..

1 个答案:

答案 0 :(得分:1)

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

应该修复它;发送&#34;附加到UI&#34;代码到UI线程并等待它完成。