Reputation: 2955
I've already searched but didn't solve my issue.
I'm simulating a TCP network on my localhost. Server listens on a port and client connects to the server. The problem is that when I close the socket by client, the Socket.Connected
remains true in the server. I need to know when clients are disconnected.
I suppose when I call Socket.Close
on client app, a TCP FIN
packet is sent to the server, right? But it seems like it doesn't.
Can you give me a solution?
P.S. I already called shutdown before closing, but the problem still persists.
Upvotes: 1
Views: 1460
Reputation: 4404
There is no notification based way to know if a client is disconnected. That is the nature of tcp/ip communication. The usual way to know if a client is connected or not is to write data to the client connection. If you get an error, you can guess that the client is disconnected. You can streamline the heuristics by looking for specific exceptions
Upvotes: 2
Reputation: 16120
While I have no practical experience with socket programming in C# it seems that Socket.Close()
does not send pending data and by implication doesn't send the FIN packet. (That is in my opinion a bit misleading because the Close
semantics seem to differ from the Stream.Close()
which calls Dispose(true)
which tries to flush if possible. Correct me if I'm wrong.)
The MSDN documentation states:
For connection-oriented protocols, it is recommended that you call Shutdown before calling the Close method. This ensures that all data is sent and received on the connected socket before it is closed.
If you need to call Close without first calling Shutdown, you can ensure that data queued for outgoing transmission will be sent by setting the DontLingerSocket option to false and specifying a non-zero time-out interval. Close will then block until this data is sent or until the specified time-out expires. If you set DontLinger to false and specify a zero time-out interval, Close releases the connection and automatically discards outgoing queued data.
Upvotes: 1