[英]C# - How to know how many bytes are left in TcpClient after perform SslStream.Read
我正在做一个客户端-服务器应用程序,服务器将检查何时有数据可用(TcpClient.Available > 0)读取,但是当它运行 SslStream.Read 时,即使我知道我需要读取多少字节,它仍然将 TcpClient.Available 设置回 0 并保留已读取的字节......我的代码未读取,因为条件 (TcpClient.Available > 0) 将是错误的,因此服务器不会对附加字节执行任何操作,直到客户端发送更多字节,这是不想要的,服务器应该尽快处理客户端发送的所有字节。 这是一些代码:
static void main()
{
TcpClient tcpClient = listener.AcceptTcpClient();
SslStream s = new SslStream(tcpClient.GetStream(), false);
//authenticate etc ...
while (true)
{
if (tcpClient.Available > 0) // now this condition is false until
// the client send more bytes
// which is not wanted
work(tcpClient);
}
}
static void work(TcpClient c)
{
//client sent 50 bytes
byte[] data = new byte[10];
s.Read(data, 0, 10); // I know this is not guaranteed to read 10 bytes
//so I have a while loop to read until it receives all the byes, this line is just for example
// do something with the 10 bytes I read, back to the while loop
}
我的“工作”实际上创建了一个新线程来完成工作并锁定该客户端直到工作完成,以便该客户端在工作完成之前不会调用工作
因为我知道运行“工作”需要多少字节,所以我只读取该字节数并解锁客户端,以便客户端可以再次“工作”
当然还有其他客户端也需要工作,这里我只展示一个来演示问题
您通常不知道要从stream读取多少字节。
但是您可以“在读取时”从 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 中读取,因为SslStream.Read返回读取的字节数!
所以你的代码变成了简单的
while (s.Read(data, 0, 10) > 0)
{
// do something with the bytes you've read
}
这是人们通常使用流的方式 - 在读取时按块读取它们。
您可以在我之前链接的文档的示例中看到它(还有更多!您应该明确地检查一下)
我变了
if (tcpClient.Available > 0)
至
if (tcpClient.Available > 0 || s.CanRead)
它按预期工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.