问题
When my client app closes the socket or even terminates my server still thinks its alive. I even check TcpClient.Connected then i see this. I bolded the important part
true if the Client socket was connected to a remote resource as of the most recent operation; otherwise, false.
How do i know if the socket is closed or not? At the moment I have to do an operation and get an exception to discover if its opened or close
回答1:
There are so many things that can break communications over a socket, many of which are totally outside your control, best keep it simple.
At the moment you have a perfectly acceptable detection mechanism, dead simple and low cost.
You could do a heart beat, send an I'm here message from the client every X somethings, and then have the server run through and see if there hadn't been one for X * fiddle factor intervals. Uses processor time and bandwidth though.
Another option depends on your client detecting it's no longer connected and requesting a new connection. If you have a unique identifier in the request , you can run through your existing connections for it, kill it, if it's there, and start then continue as normal.
I know exception doesn't feel right, but it's only really a problem if you keep losing the connection, and if you were your efforts would be better directed at sorting that out.
来源:https://stackoverflow.com/questions/12117373/how-do-i-check-if-tcpclient-is-connected