ILoggable

A place to keep my thoughts on programming

January 10, 2005 .net

TCP communication

Played around with TcpListener and TcpClient a bit this weekend. Last time I did low level network programming was in perl and it’s interface was basically a socket interface. I did multiplexing with Posix select to check on sockets that were ready to do some communication. With C# i decided to go the multi-threading route instead and use the slightly higher level interfaces TcpListener and TcpClient.

I use the listener in the main thread in non-blocking mode, using pending to decide whether to accept a new connection. Then i spawn a thread for each TcpClient and have it listen the the client.

So far so good and fairly simple stuff. Except that I can’t figure out how to detect if a client closed the connection on me rather me disconnecting them. I thought i’d get a SocketException when the client goes away, but so far my experiments show TcpClient happuily trying to read from the socket forever. Ho hum.

Update: Ok, so i’m just blind. I was so wrapped up looking for exceptions telling me that the client went away that i ignored the normal method of checking whether the read call read 0 bytes, just like in normal Posix sockets. Now that works like a charm

Leave a comment