**前言:**在现的项目中是非阻塞的情况,不可能在等待客户端来连接,请他事情不做,accept默认阻塞,使其不阻塞。如果在非阻塞情况下,SSL_accept返回值为-1.
阻塞:
unsigned long iMode = 1;
//set to non-blocking
if(ioctlsocket(listen_sock,FIONBIO, (unsigned long *)&iMode) < 0)
{
closesocket(listen_sock);
LOGERR("set socket non blocking failed!\n");
return (g_err_code = UAI_ERROR);
}
然后在调用SSL_accept的时候
while(true)
{
int SSLacceptReturnCode = SSL_accept(st_handle.handle);
if(SSLacceptReturnCode == 0)
{
LOGERR("SSL_get_error:%d\n", SSL_get_error((const SSL*)st_handle.handle, -1));
LOGERR("SSL_accpect %s\n",SSL_state_string_long((const SSL*)st_handle.handle));
SSL_shutdown((SSL*)st_handle.handle);
SSL_free((SSL*)st_handle.handle);
closesocket(iClientSocket);
SSL_CTX_free((SSL_CTX *)st_handle.context);
return (g_err_code = UAI_ERROR);
}
else if(SSLacceptReturnCode == 1)
{
break;
}
else if(SSLacceptReturnCode < 0)
{
int SSLgetErrorCode = SSL_get_error(st_handle.handle, SSLacceptReturnCode);
if(SSLgetErrorCode == SSL_ERROR_WANT_READ || SSLgetErrorCode == SSL_ERROR_WANT_WRITE)
{
/* Wait for data to be read */
continue;
}
else
{
LOGERR("SSL_get_error:%d\n", SSL_get_error((const SSL*)st_handle.handle, -1));
LOGERR("SSL_accpect %s\n",SSL_state_string_long((const SSL*)st_handle.handle));
SSL_shutdown((SSL*)st_handle.handle);
SSL_free((SSL*)st_handle.handle);
closesocket(iClientSocket);
SSL_CTX_free((SSL_CTX *)st_handle.context);
return (g_err_code = UAI_ERROR);;
}
}
else
{
LOGERR("SSL_get_error:%d\n", SSL_get_error((const SSL*)st_handle.handle, -1));
LOGERR("SSL_accpect %s\n",SSL_state_string_long((const SSL*)st_handle.handle));
SSL_shutdown((SSL*)st_handle.handle);
SSL_free((SSL*)st_handle.handle);
closesocket(iClientSocket);
SSL_CTX_free((SSL_CTX *)st_handle.context);
return (g_err_code = UAI_ERROR);;
}
}
读取的时候:
int ires = 0, count = 0;;
bool isCoutinue = true;
while (true)
{
memset(buf,'\0',sizeof(buf));
count = 0;
while (isCoutinue)
{
ires = SSL_read(ssl, buf + count, 12 - count);
int nRes = SSL_get_error(ssl, ires);
if(nRes == SSL_ERROR_NONE)
{
if(ires > 0)
{
count += ires;
if (count >= 12)
{
cout << buf << endl;
break;
}
continue;
}
}
else if (nRes == SSL_ERROR_WANT_READ)
{
continue;
}
else
{
break;
}
}
Sleep(500);
}
Handling Non-Blocking I/O Errors in OpenSSL
SSL_accept()
After result of: Select on: Try this next:
<0, SSL_ERROR_WANT_READ R SSL_accept()
<0, SSL_ERROR_WANT_WRITE W SSL_accept()
0, SSL_ERROR_SYSCALL nothing (illegal EOF)
<0, SSL_ERROR_SYSCALL see errno