gpt4 book ai didi

c# - TcpClient.Connected 返回 true 但客户端未连接,我可以使用什么代替?

转载 作者:太空狗 更新时间:2023-10-30 00:59:31 25 4
gpt4 key购买 nike

在 VB.net 中,我使用 TcpClient 来检索数据字符串。我一直在检查 .Connected 属性以验证客户端是否已连接,但即使客户端断开连接,它仍然返回 true。我可以使用什么作为解决方法?

这是我当前代码的精简版:

Dim client as TcpClient = Nothing
client = listener.AcceptTcpClient
do while client.connected = true
dim stream as networkStream = client.GetStream()
dim bytes(1024) as byte
dim numCharRead as integer = stream.Read(bytes,0,bytes.length)
dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i)
loop

如果客户端断开连接,我会认为至少 GetStream() 调用会抛出异常,但我已经关闭了另一个应用程序,但它仍然没有......

谢谢。

编辑建议轮询 Client.Available 但这并不能解决问题。如果客户端未“准确”连接可用,则返回 0。

关键是我试图让连接保持打开状态,并允许我通过同一个套接字连接多次接收数据。

最佳答案

当 NetworkStream.Read 返回 0 时,连接已经关闭。 Reference :

If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the DataAvailable property to determine if data is queued in the incoming network buffer for reading. If DataAvailable returns true, the Read operation will complete immediately. The Read operation will read as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method will complete immediately and return zero bytes.

关于c# - TcpClient.Connected 返回 true 但客户端未连接,我可以使用什么代替?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/101708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com