gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:55:46 25 4
gpt4 key购买 nike

我正在从一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com