Reputation: 6078
Ok so here is how things are going:
[Server] Start
[Server] Socket.AcceptConnection
[Client] Start
[Client] Socket.Connect
[Server] Receive //blocking
[Client] Send
[Server] Print
[Server] Receive
[Client] Close socket
Is there any way to know when the client as closed the connection? I am currently using the fake packet trick as described on MSDN where on a separate thread I do a
[Server] socket.Send(byte[], 0,0);
And I check if it throw any error but it does not, even if the client as closed the socket.
P.S. I am actualy thinking, might it be a problem if I have a socket on the server side (TCP) and a TcpClient on the client side?
Thank you.
Upvotes: 2
Views: 3392
Reputation: 1
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 & part2)
{//connection is closed
}
Upvotes: 0
Reputation: 1499770
According to the docs for Socket.Connected:
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 nonblocking, 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.
Note that your current call is a blocking call as far as I can see - you need to make a nonblocking call according to that documentation.
Upvotes: 5
Reputation: 84151
TCP connection should return 0
, i.e. EOF
, on a read from socket on which FIN has been received, but you'd be much better off designing your protocol so parties tell each other when it's time to disconnect/close the socket. Also playing with the same socket from multiple threads will bite you - avoid it.
Upvotes: 1