Because who doesn’t love a good brain-dead solution?
In case you didn’t know, when you use regular old blocking sockets, your program will just sit there waiting for something to happen until it does. This can be great if you have all the time in the world (which let’s face it, none of us do). But what if we want our programs to actually finish running before we die of old age?
Enter non-blocking sockets! With these bad boys, your program won’t just sit there waiting for something to happen. Instead, it will check and see if anything is happening, and if not, move on to other tasks until something does happen. This can be a lifesaver when you have multiple connections or need to handle large amounts of data.
In Python, making your sockets non-blocking is as easy as calling socket.setblocking(False) after creating the socket. That’s it! No more waiting around for things to happen.
But in C…well, let’s just say that things get a little more complicated. You have to choose between using O_NONBLOCK or O_NDELAY (which is almost indistinguishable from TCP_NODELAY), and you need to do it after creating the socket but before actually using it. And if you want to switch back and forth, well…good luck with that.
The major mechanical difference between blocking and non-blocking sockets is that send, recv, connect, and accept can return without having done anything. This means that you’ll need to check the return codes and error codes to see if something actually happened or not. But hey, at least your program won’t be sitting there waiting for things to happen!
It may not be a brain-dead solution, but it’s definitely worth considering if you want your programs to actually finish running before you die of old age.