How to check if TcpClient Connection is closed?
I wouldn't recommend you to try write just for testing the socket. And don't relay on .NET's Connected property either.
If you want to know if the remote end point is still active, you can use TcpConnectionInformation:
TcpClient client = new TcpClient(host, port);
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections().Where(x => x.LocalEndPoint.Equals(client.Client.LocalEndPoint) && x.RemoteEndPoint.Equals(client.Client.RemoteEndPoint)).ToArray();
if (tcpConnections != null && tcpConnections.Length > 0)
{
TcpState stateOfConnection = tcpConnections.First().State;
if (stateOfConnection == TcpState.Established)
{
// Connection is OK
}
else
{
// No active tcp Connection to hostName:port
}
}
client.Close();
See Also:
TcpConnectionInformation on MSDN
IPGlobalProperties on MSDN
Description of TcpState states
Netstat on Wikipedia
And here it is as an extension method on TcpClient.
public static TcpState GetState(this TcpClient tcpClient)
{
var foo = IPGlobalProperties.GetIPGlobalProperties()
.GetActiveTcpConnections()
.SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
return foo != null ? foo.State : TcpState.Unknown;
}
c# detecting tcp disconnect
TcpClient / NetworkStream does not get notified when the connection is closed.
The only option available to you is to catch exceptions when writing to the stream.
A few years back we moved to using sockets instead of tcp client. socket is more usable as compared to tcpclient.
there are a couple of methods that you can use
Poll is one of them
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.poll.aspx
You can also do a check on outcome of Write itself. it gives you the number of bytes actually written.
The Connected property itself only reflects the state at the last operation. Its documentation states "The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a non-blocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected."
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx
Is there a way to detect that TCP socket has been closed by the remote peer, without reading from it?
It appears the answer to my question is "no, not unless you are willing and able to modify your TCP stack to get access to the necessary private socket-state information".
Since I'm not able to do that, my solution was to redesign the proxy server to always read data from all clients, and throw away any data that arrives from a client whose partner hasn't connected yet. This is non-optimal, since it means that the TCP streams going through the proxy no longer have the stream-like property of reliable in-order delivery that TCP-using programs expect, but it will suffice for my purpose.
How to know TCP connection is closed in net package?
That thread "Best way to reliably detect that a TCP connection is closed", using net.Conn
for 'c
' (also seen in utils/ping.go
or locale-backend/server.go
or many other instances):
one := make([]byte, 1)
c.SetReadDeadline(time.Now())
if _, err := c.Read(one); err == io.EOF {
l.Printf(logger.LevelDebug, "%s detected closed LAN connection", id)
c.Close()
c = nil
} else {
var zero time.Time
c.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
}
For detecting a timeout, it suggests:
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
...
Update 2019: tuxedo25 mentions in the comments:
In go 1.7+, zero byte reads return immediately and will never return an error.
You must read at least one byte.
See commit 5bcdd63 and go issue 15735
net
: don't returnio.EOF
from zero byte reads
How to know if the client call connection close on TcpListener?
TCP is a connection-oriented protocol, but the connection still is a virtual one - the only way to know that the other party is still connected is by successfully sending or receiving a message to/from it. This is why the Connected
property may give false positives.
The 0-byte message means that the client has sent all their data and has closed (the send direction of) the socket. At that point the client still is connected, waiting for a 0-byte message back from the server (which is automatically sent when you close the server socket).
Of course in case of a network failure you would never receive that 0-byte message, but you would receive (eventually) a SocketException
instead.
See this WinSock FAQ for more information about the shutdown process.
Related Topics
Appsettings Get Value from .Config File
Post Form Data Using Httpwebrequest
Change Route Collection of MVC6 After Startup
How to Hide a Column (Gridview) But Still Access Its Value
How to Post a List of Items in MVC
Password Masking Console Application
How to Specify Proxy Credentials in Your Web.Config
Setting Up Hook on Windows Messages
Scope of Static Variable in Multi-User ASP.NET Web Application
Failed to Serialize the Response in Web API
Make Listview.Scrollintoview Scroll the Item into the Center of the Listview (C#)
Determine What Control the Contextmenustrip Was Used On
Where's the Datetime 'Z' Format Specifier
Static Generic Class as Dictionary
Accessing Google Spreadsheets with C# Using Google Data API
Correct Way Communicate Wsse Usernametoken for Soap Webservice