简体   繁体   English

Tcpclient stream.Socket / stream关闭时,ReadAsync是否不返回0?

[英]Tcpclient stream.ReadAsync does not return 0 when socket/stream closes?

I'm using TcpClient.Stream.ReadAsync to receive data in a loop. 我正在使用TcpClient.Stream.ReadAsync循环接收数据。 Traditionally, windows sockets return 0 when the socket closes gracefully. 传统上,Windows套接字正常关闭时会返回0。 With the following code, the only time ReadAsync returns is when there is actual data. 使用以下代码,只有实际数据时,ReadAsync才会返回唯一的时间。 If I close the remote app (gracefully or forcefully) or even if I call Stream.Close() on the TcpClient, the ReadAsync still doesn't complete or throw an exception. 如果我(优雅地或强制性地)关闭了远程应用程序,或者即使我在TcpClient上调用Stream.Close(),则ReadAsync仍然无法完成或引发异常。 How do I get ReadAsync to complete? 我如何完成ReadAsync?

var amountRead = await stream.ReadAsync(conn.buffer, 0, Connection.BufferSize, ct);

if (amountRead == 0)
    break; //end of stream.
else
{
    //Process Received Data here
}

No, the ReadAsync reading semantics are exactly the same as BeginRead and Read . 不, ReadAsync阅读语义与BeginReadRead完全相同。 The read will return a 0-byte result at the end of the stream. 读取在流的末尾返回0字节的结果。

It's possible that the remote server is not closing the socket gracefully. 远程服务器可能无法正常关闭套接字。 Public-facing servers often do this to avoid the 4-way closing handshake. 面向公众的服务器通常这样做是为了避免4向关闭握手。 Unfortunately, this means that you as the client need to detect when the socket is closed. 不幸的是,这意味着您作为客户端需要检测套接字何时关闭。 Traditionally, this is done by using a keepalive message or packet. 传统上,这是通过使用Keepalive消息或数据包来完成的。 I have a blog post with more details ; 我有一篇博客文章,其中有更多详细信息 but the key is it has to be an active detection - ie, the client has to send something to detect the connection is no longer there. 但关键是必须进行主动检测-即客户端必须发送一些信息以检测连接不再存在。

On a side note, I'm not sure what closing the stream would do. 附带一提,我不确定关闭会做什么。 But I'm fairly certain that closing the socket ( TcpClient ) would cause the stream read to complete with an error. 但是我相当确定关闭套接字TcpClient )会导致流读取完成并出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM