Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In general you should be able to use the <code>Connected</code> property on the <code>TcpCient</code> instance:</p> <p>See here:<br> <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected.aspx</a></p> <p>However:</p> <blockquote> <p>Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions.</p> </blockquote> <p>Try the following to make sure the <code>Connected</code> flag holds the most recent state:</p> <pre><code>var tcpClient = new TcpClient (); tcpClient.Connect(); var stream = tcpClient.GetStream(); // buffer size need to be &gt; 0 int[] buffer = new int[1]; stream.Read(buffer, 0, 0); if(!tcpClient.Connected) // do something </code></pre> <p>Based on decompilation it should be possible to read <code>0</code> bytes from a stream, at least there is no check in the .NET Framework <code>TcpClient</code> that prevents this. However it might not be aloud in the external code that is called from the framework to actually read from the network stream.</p> <p>Be sure to <code>Dispose</code> of both the <code>TcpClient</code> and the <code>Stream</code> after your done, disposing the <code>TcpClient</code>does not dispose of the <code>Stream</code> so you need todo this manually, afterwards all resources are freed up (after GC).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload