views:

243

answers:

3

I use Winsock 2 in C++, and wonder how to make my server stop reading from the client connection. The reading thread gets blocked in recv() and I have no idea how to abort it. One way to do this is use non-blocking sockets with select(), but this thread has to wait before checking the new select().

What is the proper way to stop reading the socket?

A: 

To abort the blocking call to recv(), you can close the socket with closesocket() from another thread. Even if it's a bit ugly, it should work.

You can try to shutdown() the socket too (I never tested that).

Christophe Vu-Brugier
+1  A: 

If your program has other things to do besides working with socket I/O, you should not block in the first place.

You claim your thread must wait, but that's just a reflection of your program's current design. You should redesign it so it works with some form of non-blocking sockets. Every networking problem can be addressed using non-blocking sockets.

Since you're using Winsock, you have many alternatives here, not just select(). select() is a good choice only if your application must run on many platforms and you are unable to use the superior (but mutually incompatible) alternatives available on every modern platform.

Warren Young
A: 

After I read your response, I got an idea. It end up with setsockopt(). I use it to set time out for recv(), If it's timeout, I just check if system still wanna read from this socket or not.

This way make reading thread spend most of the time waiting for incoming packet in recv().

Thank you, Voteforpedro