SslStream.ReadByte()阻塞线程?

时间:2010-06-13 13:42:12

标签: c# networking imap

我正在尝试编写一个Imap4客户端 为此,我使用SslStream连接到服务器 一切都很好,直到我发送“登录”命令 当我试图得到它的答案时,SslStream.ReadByte()阻止该线程 结果是我的程序总是崩溃 这是怎么回事?

代码:                

 if (ssl)
{
     s = stream;
}

int cc = 0; MessageBox.Show("entered"); while (true) { int xs = s.ReadByte(); MessageBox.Show(xs.ToString()); if (xs > 0) { buf.Add((byte)xs); cc++; if (xs == '\n') { break; } if (cc > 10) MessageBox.Show(en.GetString(buf.ToArray())); } else { break; } } MessageBox.Show("left");

2 个答案:

答案 0 :(得分:4)

是的,Stream.ReadByte()会阻止,直到:

  • 关闭流(在这种情况下返回-1)
  • 在流上接收数据,在这种情况下将返回下一个字节

因此,您所连接的服务器可能不会发送任何数据......它可能正在等待您提供更多数据。您是否确信您的登录命令正确发送?你刷过你正在写的小溪了吗?发送了所需的任何分隔符或行终止符?

答案 1 :(得分:0)

对于遇到这种情况却没有回答您的问题的人,我找到了以下解决方案,以解决Stream.Read()阻塞线程的问题。

NetworkStream stream = client.GetStream();
while (true)
{
    while (stream.DataAvailable == true)
    {
        input = stream.Read();
        // --- do whatever with the input
    }
}

在我的生命中,我无法弄清线程为何停止。 特别是当VS中的工具提示弹出窗口显示时,

Reads a byte from the stream and advances the position in the stream
by one byte, or returns -1 if at the end of the stream.

除非关闭流,否则它什么也不会阻止或不提供-1。

相关问题