1

I am using a TcpClient object to send and receive data. When a client loses its connection, I can see by using TcpView that its associated connection is in a CLOSE_WAIT state. Is it possible in c# to see the state of a socket? I simply want to detect the CLOSE_WAIT state so I can close the socket on the server end. I understand that I can wait to receive bytes for a certain amount of time and then close the connection if nothing is received. I just would rather close the socket and its thread immediately. Is the socket's state able to be detected on the c# side? The TcpView program can determine this. Can a c# program do this?

steven
  • 347
  • 1
  • 2
  • 10

1 Answers1

0

It's not ideal, but if you check socket.Available, it'll throw a SocketException. You still need to check the reason, though.

Also not ideal, because it's a bit clunky, is to call Poll() (with SelectRead). If it returns true, either there's data to read or the connection is closed. If there's no data to read, then that's your answer.

John C
  • 1,931
  • 1
  • 22
  • 34
  • Thanks. My current clunky solution is to simply try to send one byte to the client and catch the socket exception if the client has disconnected. I just don't want to rely on exceptions to end a session. Using Poll() with SelectWrite might actually be a better way of what I'm doing. Still, I would like to be able to check the tcp status (established, close_wait, etc) for the socket. I'm trying to somehow get a TcpConnectionInformation object that corresponds to the socket at hand, but have not figured it out if it's possible. – steven May 15 '14 at 15:37
  • Poll() with SelectWrite still returns true if the connection is in the close_wait state. I can't use SelectRead because the client may not have sent its message yet. – steven May 15 '14 at 15:58
  • I'll look into the `TcpConnectionInformation` thing later, hopefully; you're right that just knowing the status would be clearer. `SelectRead` is definitely the way to go, though, because it tells you if there's something going on _to_ read. The follow-up condition (trying to read more data) tells you whether it's data or a closed connection. Like I said, not ideal... – John C May 15 '14 at 16:26
  • Thanks. I'd like to understand how to implement this check with poll() and SelectRead. If the client has not yet sent a message, then there is no data to read, but that doesn't mean the client has disconnected. It may still be working on something before sending. – steven May 15 '14 at 21:27
  • Sorry, sorry. If there's no data to read (and the connection is good), `Poll()` returns `false`. I should have made that clearer in the first place. In the lower-level APIs (`socket.h` in C), you talk about "read activity," here, so it's obvious. – John C May 15 '14 at 22:57