我正在尝试编写一个非阻塞连接,当我使用下面的代码执行BIO_do_handshake()时,它总是返回0。我知道您不一定需要'do_handshake()',但似乎所有的事情都应该这样做,以确保握手完成。
我应该调用BIO_should_retry()吗?
void SSLAdaptor::Connect( SSL_CTX *ctx
, const std::string &hostname
, int port
, bool nonBlocking )
{
struct hostent *hp;
struct sockaddr_in addr;
SOCKET sockFD;
if( !( hp = gethostbyname( hostname.c_str() ) ) )
{
return;
}
memset( &addr, 0, sizeof( addr ) );
addr.sin_addr= *( struct in_addr* )hp->h_addr_list[0];
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
if( ( sockFD =socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) <0 )
{
return;
}
if(connect(sockFD,(struct sockaddr *)&addr, sizeof(addr))<0)
{
return;
}
SSL *ssl;
BIO *sbio;
ssl = SSL_new( ctx );
sbio = BIO_new_socket( sockFD, BIO_NOCLOSE );
SSL_set_bio( ssl, sbio, sbio );
if( SSL_connect( ssl ) <= 0 )
{
return;
}
long hsReturn = BIO_do_handshake( sbio );
if ( hsReturn <= 0 )
{
return;
}
}我的(非阻塞) BIO读取返回垃圾:实际:↨♥+o 1E¿={²²∙?φáD‘öqñ↨≈☺预期:这是一条测试消息
int SSLSocket::BIORead( std::string &buffer, const int size )
{
int bytesRead = -1;
std::vector<char> readBuffer(size);
std::cout << "Before BIO_read() call" << std::endl;
bytesRead = BIO_read( m_bio, readBuffer.data(), size );
std::cout << "After BIO_read() call" << std::endl;
std::cout << "BIO_read() read : " << bytesRead << " bytes" << std::endl;
std::string tmpBuffer = std::string( readBuffer.begin(), readBuffer.end() );
std::cout << "BIO_read() buffer : " << tmpBuffer << " bytes" << std::endl;
if ( bytesRead < 0 )
{
// Check if should retry read, if not then an error on the connection
// has occurred and the user notified.
if ( BIO_should_retry( m_bio ) )
{
bytesRead = 0;
}
else
{
// real error
bytesRead = -1;
}
}
else if ( bytesRead == 0 )
{
// Nothing was read
bytesRead = 0;
}
else
{
buffer = std::string( readBuffer.begin(), readBuffer.end() );
}
return bytesRead;
}发布于 2014-05-12 02:13:16
SSL_connect已经做了握手,但你必须正确地使用它与非阻塞套接字,例如,检查SSL_ERROR_WANT_READ,SSL_ERROR_WANT_WRITE,并等待所需的条件,只要SSL_connect返回<0。因此不需要调用BIO_do_handshake。
https://stackoverflow.com/questions/23592013
复制相似问题