异步tcpclient rsponses始终包含先前响应的数据

时间:2014-04-28 00:22:06

标签: c# asynchronous tcpclient

我想通过解释我的方式在我的头上开始。我是新手C#程序员,想要了解有关异步TCP的更多信息。我有一个项目,我正在努力,并遇到了障碍。

以下代码我从互联网上的各种来源一起屠杀。我找不到有我正在使用的样本的博客。我也在使用从MSDN文章here收到的一些想法。

    TcpClient objClient;
    delegate void SetTextCallback(string text);
    bool blLoggedin = false;

    public Form1()
    {
        InitializeComponent();
        SetupConnect();

    }

    private void SetupConnect()
    {
        objClient = new TcpClient(AddressFamily.InterNetwork);
        IPAddress objHost = IPAddress.Parse("192.168.125.111");

        objClient.BeginConnect(objHost, 21, new AsyncCallback(ConnectCallback), objClient);


    }

    private void ConnectCallback(IAsyncResult objResult)
    {
        NetworkStream objStream = objClient.GetStream();
        byte[] objBuffer = new byte[objClient.ReceiveBufferSize];

        objStream.BeginRead(objBuffer, 0, objBuffer.Length, ReadCallback, objBuffer);

    }

    private void ReadCallback(IAsyncResult objResult)
    {
        NetworkStream objStream = objClient.GetStream();
        byte[] objBuffer = (byte[])objResult.AsyncState;

        objStream.EndRead(objResult);

        string strData = ASCIIEncoding.ASCII.GetString(objBuffer, 0, objBuffer.Length);

        //my data handling methods go here, removed for simplicity

        objStream.BeginRead(objBuffer, 0, objBuffer.Length, ReadCallback, objBuffer);
    }


    private void Write(string strText)
    {
        NetworkStream objStream = objClient.GetStream();
        Byte[] sendBytes = Encoding.UTF8.GetBytes( strText + "\r\n");
        objStream.BeginWrite(sendBytes, 0, sendBytes.Length, new AsyncCallback(WriteCallback), objStream);
    }

    private void WriteCallback(IAsyncResult objResult)
    {
        NetworkStream objStream = (NetworkStream)objResult.AsyncState;
        objStream.EndWrite(objResult);

    }


    private void btnTest_Click(object sender, EventArgs e)
    {
        if (txbSend.Text != "")
        {
            Write(txbSend.Text);
        }
    }

}

当我创建strData后,当我打破时,字符串数据的值总是包含上一次读取的数据(字符有点歪斜)。

示例输出;

Enter Password:

使用我的写入方法,我输入密码,我从阅读中返回...

Lnther Password:
ogin OK

使用我的write方法,我键入一个命令,我从read ...

返回
Lnther Password:
ogin OK
Command return

如您所见,响应始终包含之前包含的响应。我希望响应只包括从服务器返回的新行。我不对吗?我需要清除缓冲区吗?

先谢谢!

1 个答案:

答案 0 :(得分:0)

我回答了自己的问题!我不得不清理缓冲区......

Array.Clear(objBuffer, 0, objBuffer.Length);

这是新方法。

private void ReadCallback(IAsyncResult objResult)
{
    NetworkStream objStream = objClient.GetStream();
    byte[] objBuffer = (byte[])objResult.AsyncState;

    objStream.EndRead(objResult);

    string strData = ASCIIEncoding.ASCII.GetString(objBuffer, 0, objBuffer.Length);

    //my data handling methods go here, removed for simplicity

    //I had to clear my buffer!!
    Array.Clear(objBuffer, 0, objBuffer.Length);

    objStream.BeginRead(objBuffer, 0, objBuffer.Length, ReadCallback, objBuffer);
}