C#Networkstream.read()Networkstream、read

2023-09-03 12:40:34 作者:Ru-花姒鈺。

如何读取(缓冲区,偏移,长度)的实际工作,如果我通过阅读为32的长度,这是否意味着它会继续阻止,直到它接收到的32个字节?

How does read(buffer, offset, length) actually work, if i pass the length to read as 32, does that mean that it would keep blocking till it receives the 32 bytes?

据我所知它会返回和异常或0的情况下,插座异常或者连接被关闭,分别为。

I understand it would return and exception or 0 in case of socket exception or if the connection is closed, respectively.

如果发送者只发送31字节,会读继续阻止? 如果这是真的,这是否意味着读总是返回整数等于长度传递给它?以及如何cnan我控制超时如果剩余1个字节不来一定的时间之后。

what if the sender only sends 31 bytes , would read continue to block? if that is true, does it mean that read would always return the integer that is equal to length passed to it? and also how cnan i control the timeout if the remaining 1 byte does not come after certain time.

重要,但没有回答

相反,如果发送端发送32字节,这是否确保读会阻塞,直到所有32接收还是可以出来了没有阅读完所有的32个字节。

推荐答案

没有,也不会封锁。 读取操作读取尽可能多的数据是可用的,最多为所述尺寸参数指定的字节数。 资料来源:的http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read.aspx

No, it will not block. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. Source: http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read.aspx

由于它不会等到额外的1个字节,如果你期待,你应该实现一个循环来继续读流。你可以退出,但是你觉得最好的循环。

Given it will not wait for that extra 1 byte, if you are expecting it, you should implement a loop to continue reading the stream. You can exit the loop however you feel best.

更新: 我错了,当我说有没有阻止的。如果没有可用的数据读取,读取方法返回0,但当我说,它不会阻塞等待填补整个缓冲区我是正确的在Kazoom的问题,它的场景描述。

UPDATE: I was wrong when I stated "There's no blocking at all. If no data is available for reading, the Read method returns 0", but I was correct when I stated that it wouldn't block waiting to fill the entire buffer which it the scenario described in Kazoom's question.

更新,以证明NetworkStream.Read块等待第一个字节,而不会阻塞等待填补整个缓冲区

Updated to demonstrate that NetworkStream.Read blocks waiting for the first byte, but does not block waiting to fill the entire buffer.

创建到控制台项目

在一端,你有监听器:


IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
TcpListener listener = new TcpListener(ep);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream s = client.GetStream();
byte[] buffer = new byte[32];
Console.WriteLine(s.Read(buffer, 0, 32));
Console.WriteLine("Press any key to continue...");
Console.Read();

在另一端,我们只发送一个字节:

On the other end, we send only one byte:


IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
TcpClient client = new TcpClient();
client.Connect(ep);
client.GetStream().Write(new byte[] { 60 }, 0, 1);
Console.WriteLine("Press any key to continue...");
Console.Read();

双方将运行,直至达到Console.Read()。请注意,听者不上读取块。

Both sides will run until they reach Console.Read(). Notice that the listener does not block on Read.

监听器将打印1

 
精彩推荐
图片推荐