我正在尝试使用 TcpListener
来收听一些数据。
我正在发送此请求(来自 Fiddler):
GET http://localhost:10000/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:10000
监听器在这里:
internal static class Program
{
private static void Main(string[] args)
{
const int PORT = 10000;
var ipAddressParts = new byte[] {127, 0, 0, 1};
var ipAddress = new IPAddress(ipAddressParts);
var server = new TcpListener(ipAddress, PORT);
const int BUFFER_SIZE = 256;
Console.WriteLine($"Starting on {ipAddress}:{PORT}.");
server.Start();
while (true)
{
var client = server.AcceptTcpClient();
Console.WriteLine("Client accepted");
var stream = client.GetStream();
var readCount = default(int);
var data = new List<byte[]>();
do
{
var buffer = new byte[BUFFER_SIZE];
readCount = stream.Read(buffer, 0, buffer.Length); // Read hanging here.
Console.WriteLine($"Received {readCount} bytes.");
if (readCount != 0)
{
Console.WriteLine(ASCII.GetString(buffer));
}
data.Add(buffer);
} while (readCount != 0);
var message = ASCII.GetBytes($"{DateTime.Now:D} Hello World!!!");
stream.Write(message, 0, message.Length);
stream.Close();
}
}
}
监听器按预期工作并接收并打印消息,输出:
Starting on 127.0.0.1:10000.
Client accepted
Received 62 bytes.
GET / HTTP/1.1
User-Agent: Fiddler
Host: localhost:10000
但是,它会在下一个循环中的下一个读取操作挂起。我知道没有更多数据要读取,所以我希望它为读取的字节返回零,然后退出循环。
MSDN Documentation暗示这是使用它的正确方法。
我应该使用什么条件来检查读取结束?
最佳答案
在您的 do-while 循环检查中,使用 DataAvailable 属性而不是您自己的 readCount。可在此处找到文档:https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.dataavailable?view=netframework-4.8 这看起来像:
做{
...
} while (stream.DataAvailable);
关于c# - 读取所有字节后 TcpListener 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57183655/