tags:

views:

511

answers:

2

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.

A: 

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.

Nikolai N Fetissov
What should happen when the client connection is interrupted? (i.e. No gracefull fail option :(, the server will be stuck on receive no?)
Drahakar
I don't know .NET socket API, but would imagine you'd get an exception. Native C API returns -1 and specific error depends on what exactly happened - RST was received, timeout elapsed, etc.
Nikolai N Fetissov
Nah, that's what I thought but when I try to send with my other thread on a closed socket, it returns 0, no exception, everything seems fine.
Drahakar
Well, Send() returns number of bytes sent, you give it zero, it sends zero :) Check the documentation on what Receive() should return on FIN-ed socket - I bet it's -1 or zero, i.e. a special value.
Nikolai N Fetissov
+4  A: 

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.

Jon Skeet