TcpClient.Connected返回true,但客户端没有连接,我可以用什么代替? [英] TcpClient.Connected returns true yet client is not connected, what can I use instead?

查看:677
本文介绍了TcpClient.Connected返回true,但客户端没有连接,我可以用什么代替?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VB.net我使用的TcpClient检索数据的字符串。我经常检查.Connected属性来验证,如果连接的客户端,但即使客户端断开这仍然返回true。我可以作为一个解决方法吗?

In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this?

这是我目前的code一个精简版:

This is a stripped down version of my current code:

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()调用将抛出一个异常,但我已经关闭了其他应用程序,它仍然不...

I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't...

感谢。

修改 轮询Client.Available建议,但这并不解决问题。如果客户端是不是'实际上可以'连接可用只是返回0。

EDIT Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0.

关键的是,我试图使连接保持开放,让我来接收数据多次在同一个套接字连接。

The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection.

推荐答案

在NetworkStream.Read返回0,则连接已关闭。 <一href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx">Reference:

When NetworkStream.Read returns 0, then the connection has been closed. Reference:

如果没有数据可用于看书,NetworkStream.Read方法将阻塞,直到数据可用。为了避免阻塞,您可以使用DataAvailable属性来确定数据是否排队的传入网络缓冲区读取。如果DataAvailable返回true,则读取操作将立即完成。如可用,最多为所述尺寸参数指定的字节数的读操作将读取尽可能多的数据。 如果远程主机关闭连接,所有可用的数据已经收到,Read方法将立即完成并返回零字节。

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.

这篇关于TcpClient.Connected返回true,但客户端没有连接,我可以用什么代替?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆