首页 > 解决方案 > 为什么我在此示例中通过套接字传输数据时丢失了字节?

问题描述

我正在尝试异步接收数据并将其存储到 StringBuilder 中,当 StringBuilder 长度大于 1000 时处理此数据。每次我调用我的 Update_Interface 函数时,都会丢失一些数据。我将缓冲区大小设置为 256。我该如何解决这个问题?这是因为我的功能需要一些时间来处理我的数据,然后客户端没有接收数据?

 public void Receive(Socket client)
    {

        try
        {
            // Create the state object.  
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.  
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }


    }

    public void ReceiveCallback(IAsyncResult ar)
    {

        try
        {
       

            // Retrieve the state object and the client socket
            // from the asynchronous state object.  
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.  
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.  

                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));


                if (state.sb.Length > 1000)
                {
                    Update_Interface(state.sb.ToString());
                    state.sb.Clear();




                }
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {

                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }

    }

标签: c#winformstcpclient

解决方案


推荐阅读