c# – TcpClient.Connected返回true但客户端未连接,我可以使用什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – TcpClient.Connected返回true但客户端未连接,我可以使用什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1407字,纯文字阅读大概需要3分钟。
内容图文
![c# – TcpClient.Connected返回true但客户端未连接,我可以使用什么?](/upload/InfoBanner/zyjiaocheng/812/287c735cfe96457b9b24364cf13418dc.jpg)
在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被建议,但这并没有解决问题.如果客户端没有’acutally’连接可用,则返回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但客户端未连接,我可以使用什么?全部内容,希望文章能够帮你解决c# – TcpClient.Connected返回true但客户端未连接,我可以使用什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。