无法使用txtStatus.Text显示接收的数据,但能够使用txtStatus.AppendText

时间:2015-05-19 06:27:40

标签: c# tcp textbox server

我正在做一个TCP服务器&客户沟通。我想在服务器的文本框中显示收到的数据(来自客户端)。

当我使用txtStatus.AppendText时,它完全正常。但是当我改为txtStatus.Text时,文本框中没有显示任何内容。

任何人都可以帮我吗?

这是我服务器的代码:

private void btnListen_Click(object sender, EventArgs e)
    {
        IPAddress ipaddress = new IPAddress(new byte[] { 123, 123, 123, 123 });
        //IPAddress ipaddress = IPAddress.Parse(txtIP1.Text + "." + txtIP2.Text + "." + txtIP3.Text + "." + txtIP4.Text);
        //int portNum = Convert.ToInt32(txtPort.Text);
        int portNum = 8500;
        TCPServerHelper.AcceptConnection(ipaddress, portNum);
        txtStatus.Text = "Connected to remote client!";

        while (true)
        {
                byte[] bufferReceivedData = TCPServerHelper.Read();
                MovementData recMovementData = (MovementData)TCPServerHelper.Deserialize(bufferReceivedData);

                try
                {
                    //txtStatus.AppendText(recMovementData.BaseMoveData.BaseMov.ToString());
                    txtStatus.Text = recMovementData.BaseMoveData.BaseMov.ToString();

                    DataHandler(recMovementData.BaseMoveData.BaseMov.ToString());
                }

                catch
                { }

            }
    }

    delegate void DataHandlerDelegate(string Direction);
    public void DataHandler(string Direction)
    {
        if (!this.InvokeRequired)
        {
            switch(Direction)
            {
                case "stop":
                    txtResult.Text = "stop";
                    break;

                case "forward":
                    txtResult.Text = "forward";
                    break;

                case "backward":
                    txtResult.Text = "backward";
                    break;

                case "left":
                    txtResult.Text = "left";
                    break;

                case "right":
                    txtResult.Text = "right";
                    break;

                case "clockwise":
                    txtResult.Text = "clockwise";
                    break;

                case "anti-clockwise":
                    txtResult.Text = "anti-clockwise";
                    break;

                default:
                    break;
            }
        }
        else
        {
            BeginInvoke(new DataHandlerDelegate(DataHandler), new object[] { Direction });
        }
    }

0 个答案:

没有答案