TcpClient.Connected返回true,但客户端未连接,该怎么用呢?

时间:2020-03-06 14:25:51  来源:igfitidea点击:

在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。

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

解决方案

而不是轮询client.connected,也许可以使用NetworkStream的属性来查看是否没有更多可用数据?

无论如何,在ONDotnet.com上有一篇文章,其中包含大量关于侦听器及其他方面的信息。应该可以解决问题...

当NetworkStream.Read返回0时,则连接已关闭。参考:

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.

更好的答案:

if (client.Client.Poll(0, SelectMode.SelectRead))
                    {
                        byte[] checkConn = new byte[1];
                        if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
                        {
                            throw new IOException();
                        }
                    }