非阻塞连接的OpenSSL [英] Non-blocking connect OpenSSL

查看:2943
本文介绍了非阻塞连接的OpenSSL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个常规的C座。一旦连接,它返回 EWOULDBLOCK / WSAEWOULDBLOCK 如预期,因为我所做的:

I created a regular C socket. Upon connect, it returns EWOULDBLOCK/WSAEWOULDBLOCK as expected because I did:

unsigned long int mode = 0;
ioctlsocket(ssl_info->sock, FIONBIO, &mode);
setsockopt(ssl_info->sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
setsockopt(ssl_info->sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));

把插座非阻塞模式。从那以后,我做的:

to put the socket in non-blocking mode. After that I do:

ssl = SSL_new(ctx);
SSL_set_fd(ssl, sock);
return SSL_connect(ssl);

但是,它返回-1。

However, it returns -1.

我看网上,这意味着我需要处理 SSL_ERROR_WANT_READ SSL_ERROR_WANT_WRITE

I read online that it means I need to handle SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE.

所以我所做的:

int res = -1;
while(res == -1)
{
    res = SSL_connect(ssl);
    switch (SSL_get_error(ssl, res))
    {
        case SSL_ERROR_WANT_CONNECT:
        MessageBox(NULL, "Connect Error", "", 0);
        break;

        case SSL_ERROR_WANT_READ:   //prints this every time..
        MessageBox(NULL, "Read Error", "", 0);
        break;

        case SSL_ERROR_WANT_WRITE:
        MessageBox(NULL, "Write Error", "", 0);
        break;
    }

    SelectSocket(ssl);
}

std::cout<<"Connected!\n";

其中, SelectSocket 的定义是:

bool SelectSocket(SSL* ssl)
{
    if (blockmode)
    {
        fd_set readfds;
        fd_set writefds;
        FD_ZERO(&readfds);
        FD_ZERO (&writefds);
        FD_SET(ssl_info->sock, &readfds);
        FD_SET(ssl_info->sock, &writefds);

        struct timeval tv = {0};
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = timeout % 1000;
        return select(sock + 1, &readfds, &writefds, NULL, &tv) >= 0;
    }

    return select(sock + 1, NULL, NULL, NULL, NULL) != SOCKET_ERROR;
}

所以,我能得到究竟怎么连接?我似乎无法能够读取或者套接字是非阻塞写什么:S。

So how exactly can I get it to connect? I can't seem to be able to read or write anything when the socket is non-blocking :S.

任何想法?

推荐答案

(-1),以返回所以SSL_connect()表示基础BIO不能满足所以SSL_connect()的需求继续握手。

The (-1) returned by SSL_connect() indicates that the underlying BIO could not satisfy the needs of SSL_connect() to continue the handshake.

一般情况下,调用进程则要采取适当的行动,以满足所以SSL_connect的需要()后重复呼叫。

Generally, the calling process then must repeat the call after taking appropriate action to satisfy the needs of SSL_connect().

然而,在使用非阻塞套接字时,没有什么是必须要做的;但选择()可以用来检查所需的条件。

However, when using a non-blocking socket, nothing is to be done; but select() can be used to check for the required condition.

(当使用一个缓冲BIO,就像一个BIO对,必须将数据写入或能够继续之前检索出来的生物。)

(When using a buffering BIO, like a BIO pair, data must be written into or retrieved out of the BIO before being able to continue.)

这篇关于非阻塞连接的OpenSSL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆