c# - How to check if TcpClient Connection is closed? -
c# - How to check if TcpClient Connection is closed? -
i'm playing around tcpclient , i'm trying figure out how create connected property false when connection dropped.
i tried doing
networkstream ns = client.getstream(); ns.write(new byte[1], 0, 0);
but still not show me if tcpclient disconnected. how go using tcpclient?
i wouldn't recommend seek write testing socket. , don't relay on .net's connected property either.
if want know if remote end point still active, can utilize 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 ok } else { // no active tcp connection hostname:port } } client.close();
see also: tcpconnectioninformation on msdn ipglobalproperties on msdn description of tcpstate states netstat on wikipedia
and here extension method on tcpclient.
public static tcpstate getstate(this tcpclient tcpclient) { var foo = ipglobalproperties.getipglobalproperties() .getactivetcpconnections() .singleordefault(x => x.localendpoint.equals(tcpclient.client.localendpoint)); homecoming foo != null ? foo.state : tcpstate.unknown; }
c# sockets tcpclient networkstream
Comments
Post a Comment