我想知道为什么 NetworkStream 中的 while 不立即执行并等待

发布于 2025-01-10 20:40:05 字数 789 浏览 2 评论 0原文

我有一个服务器程序。 还有一个客户端程序。

服务器是使用 TcpListener 创建的,客户端是使用 TcpClient 创建的。

经过多次实验,下面代码中的while直到客户端程序中执行stream.write()才被执行。

你能说出这是什么原理吗?

while (true) // That's no!
{
  Console.WriteLine("waiting connection...");

  TcpClient client = server.AcceptTcpClient();
  Console.WriteLine("Connected!");

  data = null;

  NetworkStream stream = client.GetStream();

  int i;
  // This is while
  while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  {
    data = Encoding.UTF8.GetString(bytes, 0, i);
    Console.WriteLine("Received: {0}", data);
  }

  Console.WriteLine("This statement is only executed when stream.write() is executed.");

  client.Close();
}

I have a server program.
And there is also a client program.

The server was created using TcpListener, and the client was created using TcpClient.

After several experiments, while in the code below is not executed until stream.write() is executed in the client program.

Can you tell by what principle this is?

while (true) // That's no!
{
  Console.WriteLine("waiting connection...");

  TcpClient client = server.AcceptTcpClient();
  Console.WriteLine("Connected!");

  data = null;

  NetworkStream stream = client.GetStream();

  int i;
  // This is while
  while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  {
    data = Encoding.UTF8.GetString(bytes, 0, i);
    Console.WriteLine("Received: {0}", data);
  }

  Console.WriteLine("This statement is only executed when stream.write() is executed.");

  client.Close();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷到爆炸 2025-01-17 20:40:05

您指的是哪个while,外部还是内部?

在客户端写入流之前,服务器执行到什么程度?
通过几个断点应该很容易弄清楚。

TcpClient client = server.AcceptTcpClient(); 将阻塞,直到请求客户端的连接。

To which while are you referring, the outer or inner one?

Up to what point DOES the server execute before the client writes to the stream?
That should be easy to figure out with a few breakpoints.

TcpClient client = server.AcceptTcpClient(); will block until a connection from the client is requested.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文