我想知道为什么 NetworkStream 中的 while 不立即执行并等待
我有一个服务器程序。 还有一个客户端程序。
服务器是使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您指的是哪个
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.