The whole logic of my application works with non-blocking sockets, but in the connection phase I found it better to make the socket blocking, before performing the SSL handshake with SSL_connect()
. This is because otherwise it created a busy loop until the handshake finished successfully, and actually blocking the socket until then should be more efficient.
Here is the pseudo-code to my connect logic:
bool connect(host)
{
int socket;
init_socket(socket);
set (socket, NONBLOCKING);
connect_with_timeout(socket, host, 2s);
if (timeout_failed || connect_errors) return false;
set (socket, BLOCKING);
SSL_connect (socket);
if (ssl_connect_errors) return false;
set (socket, NONBLOCKING);
return true;
}
And the SSL handshake on non-blocking sockets looks like this:
do
{
SSL_connect(socket);
}
while (!SSL_connection_errors);
Is it considered a bad practice to change socket type like this ? What really happens on a low level when you do it ?
I know this seems like a micro-improvement in performance, but I want to get it right, as my application may attempt to reconnect once every 30 seconds and the user gets the occasional less than 1s big CPU spike.
Edit: The answers I got on this question made me see how attempting read on non-blocking sockets and then sleeping is not really a good idea. However, I do need a platform-independent solution to poll
so I already went ahead and added a select
with a 1s timeout on read operations, tested for both Windows and Linux and CPU usage is lower now. Thanks.