1

我将在下面的程序开始时延迟 3 分钟。但是在超级终端中,它每 2 秒显示每个数据。

她是我下面的代码。请让我知道我哪里出错了。我该如何纠正这个延迟。有什么建议吗?

private void StartReceiving()
{
    // coding part of receiving changed.
    try
    {
        string IPStr = textBox1_IPaddress.Text.Trim();
        string portStr = textBox2_Port.Text.Trim(); 
        int port = Convert.ToInt32(portStr);

        int bytesRead = 0;
        byte[] buffer = new byte[9];
        //------------------------------------------------------------------
        IPAddress ipAddress = System.Net.IPAddress.Parse(IPStr);
        //create server's tcp listener for incoming connection

        try
        {
            textBox3.Visible = true;
            client = new TcpClient();
            client.Connect(IPStr, port);
            ns = client.GetStream();
            while (true)
            {
                if (ns.DataAvailable)
                {

                    byte[] data = ReadNumberBytes(ns, 9);
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    msg = encoder.GetString(data);
                    textBox3.AppendText(msg);
                    textBox3.AppendText("\n");
                    GetData(msg);


                }
                else
                {
                    Thread.Sleep(4000);
                    byte[] data = ReadNumberBytes(ns, 9);
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    msg = encoder.GetString(data);
                    GetData(msg);

                }
            }

            client.Close();            
        }
        catch (SocketException se)
        {
             //message box;
        }
    }  
}    


public static byte[] ReadNumberBytes(NetworkStream stream, int n)
{
    byte[] buffer = new byte[n];
    int bytesRead = 0;

    int chunk;
    while (bytesRead < n)
    {
        chunk = stream.Read(buffer, (int)bytesRead, buffer.Length - int)bytesRead);                                         

        if (chunk == 0)
        {
            // error out.
            throw new Exception("Unexpected disconnect");
        }
        bytesRead += chunk;
    }
    return buffer;
}
4

0 回答 0