c# - 确定缓冲区应该有多大

标签 c# .net windows tcp

我正在从一个 tcp 流中读取 - 我已经使用“MLSD”命令(检索文件/目录信息)查询了一个 FTP 服务器。虽然由于响应大小是可变的(取决于文件/目录等的数量),但我不确定“缓冲区”应该设置多少字节。如何确保通过 tcp 流从 FTP 服务器检索到所有数据?

 private string controlListener(int controlPort)
        {
            try
            {
                // Create a TcpClient. 
                // Note, for this client to work you need to have a TcpServer  
                // connected to the same address as specified by the server, port 
                // combination.
                controlClient = new TcpClient(ftpHost, controlPort);

                // Get a client stream for reading and writing. 
                controlStream = controlClient.GetStream();

                    // Because we don't know how many bytes are incoming for welcome message - we use a 2 second delay to retrieve all bytes within that time frame.
                    // Receive the TcpServer.response. 
                    // Buffer to store the response bytes.
                    Byte[] data = new Byte[4096];

                    // String to store the response ASCII representation.
                    String responseData = String.Empty;

                    // Get Control Stream Responce: Read the first batch of the TcpServer response bytes.
                    Int32 bytes = controlStream.Read(data, 0, data.Length);
                    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    Console.WriteLine(responseData);

                    return responseData;
            }

最佳答案

在 Mark 的回答之后......我使用了这个方法,你应该很容易看到如何合并它。

    /// <summary>
    /// Read TCP response, this simple method can be re-used elsewhere as needed later.
    /// </summary>
    /// <returns></returns>
    private static string ReadResponse(NetworkStream networkStream)
    {
        // Check to see if this NetworkStream is readable.
        if (networkStream.CanRead)
        {
            var myReadBuffer = new byte[256]; // Buffer to store the response bytes.
            var completeMessage = new StringBuilder();

            // Incoming message may be larger than the buffer size.
            do
            {
                var numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
                completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
            } while (networkStream.DataAvailable);

            return completeMessage.ToString();
        }
        return null;
    }

关于c# - 确定缓冲区应该有多大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13826323/

相关文章:

windows - 为什么我不能按顺序重定向到两个输入流 `0<` 和 `3<`?

javascript - C# 中的进度条

c# - 异步函数可以内联吗?

c# - 为什么我们需要 C# 委托(delegate)

c# - 是否可以在 Windows 7 和 Visual Studio 2012 中开发 Windows Mobile 应用程序

c# - Visual Studio 2015 封装字段

php - 对 PHP move_uploaded_file() 修改的文件的奇怪权限

php - 如何在 Windows 上的任何地方运行 .phar?

c# - 面试题: . Any() vs if (.Length > 0) 测试集合是否有元素

c# - 使用自动映射器映射异步结果