我正在尝试使用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
但是,它将挂起下一个循环中的下一个读取操作。我知道没有更多的数据要读取,所以我希望它为读取的字节返回0,然后退出循环。
MSDN Documentation暗示这是正确的使用方法。
我应该使用什么条件来检查读取的结尾?
最佳答案
在do-while循环检查中,使用dataavailable属性而不是自己的readcount。文档可以在这里找到:https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.dataavailable?view=netframework-4.8
这看起来像是:do {...} while (stream.DataAvailable);