TcpClient接收數據不全

c#在使用TcpClient一般首發數據如下:

 private string Tcp(string senddata)
        {
            try
            {
                TcpClient client = new TcpClient();
                client.Connect(ip, 6789);
                //建立連接服務端的數據流
                NetworkStream ns = client.GetStream();
                byte[] buffer = Encoding.UTF8.GetBytes(senddata);
                ns.Write(buffer, 0, buffer.Length);
                int count = 0;
                List<byte> ls = new List<byte>();

                buffer = new byte[bufferSize];
                while (true)
                {
                    count = ns.Read(buffer, 0, buffer.Length);
                    ls.AddRange(buffer);
                    buffer = new byte[bufferSize];
                    if (count < bufferSize)
                    {
                        break;
                    }
                }
                buffer = ls.ToArray();
                string recStr = Encoding.UTF8.GetString(buffer);
                client.Close();
                return recStr;
            }
            catch
            {
                return null;
            }
        }

這麼寫小量數據是沒有問題的,但是在面對大量數據時,經常會出現接收不全。但是在調試的時候,發現接收是完全的。很是奇怪。

經過多次調試發現,在接收大量數據的時候,特別是超過1k時,一定要使用Thread.Sleep(10)函數,以便cpu有時間來處理數據到緩衝區。


 private string Tcp(string senddata)
        {
            try
            {
                TcpClient client = new TcpClient();
                client.Connect(ip, 6789);
                //建立連接服務端的數據流
                NetworkStream ns = client.GetStream();
                byte[] buffer = Encoding.UTF8.GetBytes(senddata);
                ns.Write(buffer, 0, buffer.Length);
                int count = 0;
                List<byte> ls = new List<byte>();

                buffer = new byte[bufferSize];
                while (true)
                {
                    count = ns.Read(buffer, 0, buffer.Length);
                    ls.AddRange(buffer);
                    buffer = new byte[bufferSize];
                    if (count < bufferSize)
                    {
                        break;
                    }
		    Thread.Sleep(10);
                }
                buffer = ls.ToArray();
                string recStr = Encoding.UTF8.GetString(buffer);
                client.Close();
                return recStr;
            }
            catch
            {
                return null;
            }
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章